以ms-sql计算累积和

时间:2016-04-19 07:52:38

标签: 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) 

这就是我试过的

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

但是我无法获得所需的输出,非常感谢任何帮助,谢谢

3 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:2)

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

  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

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

答案 2 :(得分:1)

使用ROW_NUMBER只是按升序排列billingID,然后使用加入。

<强>查询

;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;