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:
Share on facebook
Share on twitter
Share on linkedin


The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.