Cumulative sum with group by

0

Please login or register to vote for this query.

(click on this box to dismiss)

Webmasters

Q&A for pro webmasters

DECLARE @t TABLE(ColumnA INT, ColumnB VARCHAR(50));

INSERT INTO @t VALUES
(2,           '1/1'),
(3  ,         '1/2'),
(4   ,        '1/3'),
(5    ,       '1/4'),
(1     ,      '1/1');

;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) AS ColumnA, ColumnB
FROM cteRanked c1;

/*

to this:

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

Enter Parameters

Options:
Switch to meta site
loading Hold tight while we fetch your results