我有一个具有以下结构的表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)


这就是我尝试过的

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


但我无法获得所需的输出,任何帮助将不胜感激,谢谢

最佳答案

您可以使用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




对于SQL Server 2012+,可以使用SUM OVER()

SELECT *,
    cummulative = SUM(Percent_of_Qty) OVER(ORDER BY billingId)
FROM tblSumDemo

关于sql - 在MS-SQL中计算累积总和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36711958/

10-12 15:23