SQL query for finding cumulative figures of a field/column
One thing everytime in our reporting comes the cumulative figure which we do best in excel by putting the values in a column and next to the column put a formula and drag.
But what if data resides in Database Server and we need to programmatically plot the cumulative figure to a graph and/or the from a huge number of rows you’ll need to aggregate then cumulate.
Say for example we have a table which returns when queried
Select * from dailysales
.
Date | No_Of_Sales |
2008-04-16 15:03:21.080 | 3 |
2008-04-17 15:03:21.080 | 2 |
2008-04-18 10:07:19.507 | 5 |
... | ... |
Now we need another column to show the cumulative figure like.
For that we can use the following query:
select Date, No_Of_Sales,
(select sum(No_Of_Sales)
from dailysales where Date<=d.Date) as Running_Total
from dailysales d
order by date
Which gives
Date | No_Of_Sales | Running_Total |
2008-04-16 15:03:21.080 | 3 | 3 |
2008-04-17 15:03:21.080 | 2 | 5 |
2008-04-18 10:07:19.507 | 5 | 10 |
... | ... | ... |
Comments