在日期列上运行总计

时间:2012-02-04 14:22:11

标签: sql sql-server-2008 running-total

我的表中有以下数据:

id   invoice_id   date         ammount
1    1            2012-01-01    100.00
20   1            2012-01-31     50.00
470  1            2012-01-15    300.00

现在,我需要在一段时间内计算发票的运行总额。因此,此数据样本的输出应如下所示:

id   invoice_id   date         ammount  running_total
1    1            2012-01-01    100.00         100.00
470  1            2012-01-15    300.00         400.00
20   1            2012-01-31     50.00         450.00

我试过这个样本http://www.sqlusa.com/bestpractices/runningtotal/和其他几个,但问题是我可以输入id 20,date 2012-01-31和id 120,date 2012-01-01,然后我不能使用NO = ROW_NUMBER(按日期)...在第一次选择中然后使用ID<第二次选择NO以计算跑步总数。

1 个答案:

答案 0 :(得分:0)

DECLARE @DateStart DATE='2012-01-01'; 

WITH cte 
     AS (SELECT id = Row_number() OVER(ORDER BY [date]), 
                DATE, 
                myid = id, 
                invoice_id, 
                orderdate = CONVERT(DATE, DATE), 
                ammount 
         FROM   [Table_2] 
         WHERE  DATE >= @DateStart) 
SELECT myid, 
       invoice_id, 
       DATE, 
       ammount, 
       runningtotal = (SELECT SUM(ammount) 
                       FROM   cte 
                       WHERE  id <= a.id) 
FROM   cte AS a 
ORDER  BY id 

enter image description here