Cumulative sum with group by

0

Please login or register to vote for this query.

(click on this box to dismiss)

Gardening and Landscaping

Q&A for gardeners and landscapers

DECLARE @ta TABLE(idoggetto INT, visite INT, mese INT, anno INT);

INSERT INTO @ta VALUES
(001,   6,         6, 2017),
(001,   7,         7, 2017),
(001,   8,         8, 2017),
(001,   9,         9, 2017),
(001,   11,       10, 2017),
(001,   14,       11, 2017),
(001,   7,        12, 2017),
(001,   4,         1, 2018),
(001,   0,         2, 2018),
(001,   1,         3, 2018)
;

WITH cteRanked AS (
   SELECT idoggetto, visite, mese, anno, ROW_NUMBER() OVER(ORDER BY anno, mese) rownum
   FROM @ta
   ) 

SELECT (SELECT SUM(visite) FROM cteRanked c2 WHERE c2.rownum <= c1.rownum ) 
AS visite, mese, anno, idoggetto
FROM cteRanked c1;

Enter Parameters

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