历史滚动每日总和

时间:2014-06-11 15:09:23

标签: sql loops sql-server-2008-r2

我有一张由日期和当天记录的收入金额组成的表格可以追溯到大约12年。我想对这些数据做些什么是创建一个包含日期和之前7天收入数字的新表。任何指导将不胜感激。下面是我的源表和我的结果需要看起来像什么的示例....

来源表..

DATE       |   Revenue
12/31/2013 |   200
12/30/2013 |   300
12/29/2013 |   400
12/28/2013 |   100
12/27/2013 |   200
12/26/2013 |   150
12/25/2013 |   350
12/24/2013 |   450
12/23/2013 |   200
12/22/2013 |   300
12/21/2013 |   100
12/20/2013 |   300

结果表......

DATE       |   7Dayrev
12/31/2013 |    1700 
12/30/2013 |    1950
12/29/2013 |    1850
12/28/2013 |    1750
12/27/2013 |    1750
12/26/2013 |    1850
ETC......

1 个答案:

答案 0 :(得分:1)

您可以通过相关子查询执行此操作:

;WITH cte AS (SELECT *,ROW_NUMBER() OVER(ORDER BY [DATE] DESC) RN
              FROM Table1)
SELECT a.[DATE], a.Revenue, (SELECT SUM(b.Revenue)
                             FROM cte b
                             WHERE b.RN BETWEEN a.RN-6 AND a.RN) as Rev_7Day
FROM   cte a
ORDER BY a.RN DESC 

演示:SQL Fiddle