简体   繁体   English

历史滚动每日总和

[英]Historical Rolling Daily sum

I have a table of consisting of Dates and the amount of revenue recorded for that day going back for about 12 years. 我有一张表格,其中包含日期和该日期记录的可追溯到大约12年的收入。 What I would like to do with this data is create a new table with Dates and prior 7-day revenue numbers. 我要使用此数据做的是创建一个包含日期和以前的7天收入数字的新表。 Any guidance would be greatly appreciated. 任何指导将不胜感激。 Below is an example of what my source table and what my results would need to look like.... 下面是我的源表和结果需要什么样的示例。

Source Table.. 源表

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

Resulting Table... 结果表...

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

You can do this via correlated subquery: 您可以通过相关子查询来执行此操作:

;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 

Demo: SQL Fiddle 演示: SQL Fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM