SQL Cumulative Sum累积求和

期望结果:

 ID  VAL  CumSum
 1  10  10
 2  20  30
 3  30  60

方法一: 使用分析函数

select id,val,sum(val) over ( order by id ) as CumSum from table

方法二: 如果不支持分析函数,使用join


SELECT a.id, sum(b.num) as num
from dbo.dt a
inner join dbo.dt b
    on a.id>=b.id
group by a.id

参考文章:

 http://www.sqlservercentral.com/blogs/querying-microsoft-sql-server/2013/10/19/cumulative-sum-in-sql-server-/

 

原文地址:https://www.cnblogs.com/davablog/p/5069847.html