Cumulative sum with group by

0

Please login or register to vote for this query.

(click on this box to dismiss)

スタック・オーバーフロー

プログラマーとプログラミングに熱心な人々のための質問と回答

DECLARE @t TABLE(nu INT, m VARCHAR(2), y VARCHAR(4));

INSERT INTO @t VALUES
(1,           '01', '2011'),
(26,         '10', '2020'),
(5,        '05', '2023'),
(90,       '01', '2024'),
(1,      '02', '2024');

;WITH cte
AS
(
   SELECT y, m, nu asum
   FROM @t 
  
), cteRanked AS
(
   SELECT asum, y, m, ROW_NUMBER() OVER(ORDER BY y,m) rownum
   FROM cte
) 
SELECT (SELECT SUM(asum) FROM cteRanked c2 WHERE c2.rownum <= c1.rownum) AS ColumnA, y,m
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