devxlogo

Cumulative Summary in SQL

Cumulative Summary in SQL

Question:
I need a summary-select which summaries cumulative values. This one works in Microsoft Access:

SELECT s.nl_item_id, s.nl_value, (     SELECT sum(sub.nl_value) FROM TABLE1 sub      WHERE sub.nl_item_id<=s.nl_item_id) AS kumulFROM TABLE1 AS s;

How can I make it work using a BDE-DB2 alias?

Answer:
As far as I know, you can't do this in a single step on most server databases, especially traditional systems like DB2 and Oracle. MS SQL Server's TransactSQL (I think Access uses a variant of that SQL) allows you to shortcut a lot of stuff—but as I said, most databases just won't let you do that. On those types of databases, you have to split up your work into a couple of steps.

First off, you need to create a table on your server that you can use as a working table. For this discussion, I'll use the same structure as your example above, but with an extra field that I'll call "cumul." As far as the SQL goes, it'll look something like this (mind you, I'm using ANSI SQL):

INSERT INTO CumulTbl (item_id, value)SELECT item_id, valueFROM Table1UPDATE CumulTbl C1SET cumul = (SELECT Sum(Value)             FROM CumulTbl C2             WHERE C2.item_id <= C1.item_id)

Once you've done the above, simply select from the temporary table.

Alternatively, you can add a column to the original table and merely do the update statement. Then select from the table to get your answer.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist