Cumulating value of current row + sum of previous rows

Sam picture Sam · Oct 1, 2012 · Viewed 54.1k times · Source

How would you do to transform a Column in a table from this:

ColumnA   ColumnB
2           a
3           b
4           c
5           d
1           a

to this:

ColumnA          ColumnB
3                 a
6(=3+3)           b   
10(=4+3+3)        c   
15(=5+4+3+3)      d 

I'm interested to see esp. what method you would pick.

Answer

Mahmoud Gamal picture Mahmoud Gamal · Oct 1, 2012

Like this:

;WITH cte
AS
(
   SELECT ColumnB, SUM(ColumnA) asum 
   FROM @t 
   gROUP BY ColumnB

), cteRanked AS
(
   SELECT asum, ColumnB, ROW_NUMBER() OVER(ORDER BY ColumnB) rownum
   FROM cte
) 
SELECT (SELECT SUM(asum) FROM cteRanked c2 WHERE c2.rownum <= c1.rownum),
  ColumnB
FROM cteRanked c1;

This should give you:

ColumnA    ColumnB
3             a
6             b
10            c
15            d

Here is a live demo