Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Relational Databases
Expertise: Beginner
Jul 12, 1999

Cumulative Summary in SQL

I need a summary-select which summaries cumulative values. This one works in Microsoft Access:
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 kumul
How can I make it work using a BDE-DB2 alias?

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, value
FROM Table1

UPDATE CumulTbl C1
SET 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.

DevX Pro
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.