Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Valore cumulativo della riga corrente + somma delle righe precedenti

In questo modo:

;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;

Questo dovrebbe darti:

ColumnA    ColumnB
3             a
6             b
10            c
15            d

Ecco una demo dal vivo