SQL Server - Cumulative Sum that resets when 0 is encountered

女生的网名这么多〃 提交于 2019-12-30 10:00:12

问题


I would like to do a cumulative sum on a column, but reset the aggregated value whenever a 0 is encountered

Here is an example of what i try to do :

This dataset :

pk    price
1     10
2     15
3     0
4     10
5     5

Gives this:

pk    price
1     10
2     25
3     0
4     10 
5     15

回答1:


In SQL Server 2008, you are severely limited because you cannot use analytic functions. The following is not efficient, but it will solve your problem:

with tg as (
      select t.*, g.grp
      from t cross apply
           (select count(*) as grp
            from t t2
            where t2.pk <= t.pk and t2.pk = 0
           ) g
     )
select tg.*, p.running_price
from tg cross apply
     (select sum(tg2.price) as running_price
      from tg tg2
      where tg2.grp = tg.grp and tg2.pk <= tg.pk
     ) p;

Alas, prior to SQL Server 2012, the most efficient solution might involve cursors. In SQL Server 2012+, you simply do:

select t.*,
       sum(price) over (partition by grp order by pk) as running_price
from (select t.*,
             sum(case when price = 0 then 1 else 0 end) over (order by pk) as grp
      from t
     ) t;


来源:https://stackoverflow.com/questions/50394155/sql-server-cumulative-sum-that-resets-when-0-is-encountered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!