计算累积总和以 ms-sql

Calculating cumulative sum in ms-sql

我有一个 table 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

您可以使用适用于所有版本的子查询:

  select billingid,qty,percentofqty,
  (select sum(qty) from tblsumdemo t2 where    t1.id<=t2.id) as csum
  from 
  tblsumdemo t1

您也可以使用 sql 2012 年的 windows 函数:

   select *,
   sum(qty) over (order by qty rows between unbounded PRECEDING and current row) as csum
    from tblsumdemo

这里我说的是从第一行开始计算所有行的总和(无界前行和当前行)。你可以忽略默认的无界前行和当前行

使用ROW_NUMBER只是将billingID按升序排列,然后使用join。

查询

;with cte as(
    select rn = row_number() over(
        order by billingid
    ), *
    from tblSumDemo
)
select t1.billingid, t1.qty, t1.Percent_of_qty,
sum(t2.Percent_of_qty) as cummulative
from cte t1
join cte t2
on t1.rn >= t2.rn
group by t1.billingid, t1.qty, t1.Percent_of_qty;