[英]SQL Server - Cumulative Sum that resets when 0 is encountered
我想对列进行累积求和,但只要遇到0就重置聚合值
这是我尝试做的一个例子:
这个数据集:
pk price
1 10
2 15
3 0
4 10
5 5
给出这个:
pk price
1 10
2 25
3 0
4 10
5 15
在SQL Server 2008中,由于您无法使用分析函数,因此受到严格限制。 以下效率不高,但它可以解决您的问题:
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;
唉,在SQL Server 2012之前,最有效的解决方案可能涉及游标。 在SQL Server 2012+中,您只需执行以下操作:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.