Dee*_*esh 2 sql sql-server sql-server-2008 cumulative-sum
我有一个具有以下结构的表 tblsumDemo
billingid qty Percent_of_qty cumulative
1 10 5 5
2 5 8 13(5+8)
3 12 6 19(13+6)
4 1 10 29(19+10)
5 2 11 40(11+10)
Run Code Online (Sandbox Code Playgroud)
这是我尝试过的
declare @s int
SELECT billingid, qty, Percent_of_qty,
@s = @s + Percent_of_qty AS cumulative
FROM tblsumDemo
CROSS JOIN (SELECT @s = 0) AS var
ORDER BY billingid
Run Code Online (Sandbox Code Playgroud)
但我无法获得所需的输出,任何帮助将不胜感激,谢谢
您可以使用CROSS APPLY:
SELECT
t1.*,
x.cumulative
FROM tblSumDemo t1
CROSS APPLY(
SELECT
cumulative = SUM(t2.Percent_of_Qty)
FROM tblSumDemo t2
WHERE t2.billingid <= t1.billingid
)x
Run Code Online (Sandbox Code Playgroud)
对于 SQL Server 2012+,您可以使用SUM OVER():
SELECT *,
cummulative = SUM(Percent_of_Qty) OVER(ORDER BY billingId)
FROM tblSumDemo
Run Code Online (Sandbox Code Playgroud)