Friday, January 31, 2020

SQL SERVER - How to make cumulative sum column

If you need cumulative sum if SQL select, you can use analytical function:
select  cast( mag as int ) as mag, count(*) as count,
sum ( count(*) ) over 
( order by cast( mag as int ) rows between unbounded preceding and current row ) 
as count_cumul
from dso
where
catalog = 'MYDSO'
group by cast( mag as int )
order by cast( mag as int )
Output:
mag         count       count_cumul
----------- ----------- -----------
0           5           5
1           5           10
2           7           17
3           13          30
4           26          56
5           45          101
6           88          189
...

No comments:

Post a Comment