Cumulative Summary in SQL

Cumulative Summary in SQL

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?

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.

Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved