我有一张按小时计算产品使用量(产品被使用的次数)的表格数据 -
ID (bigint)| ProductId (tinyint)| Date (int - YYYYMMDD) | Hour (tinyint)| UsageCount (int)
#|1 | 20140901 | 0 | 10
#|1 | 20140901 | 1 | 15
#|1 | 20140902 | 5 | 25
#|1 | 20140903 | 5 | 25
#|1 | 20140904 | 3 | 25
#|1 | 20140905 | 7 | 25
#|1 | 20140906 | 10 | 25
#|1 | 20140907 | 9 | 25
#|1 | 20140908 | 5 | 25
#|2 | 20140903 | 16 | 10
#|2 | 20140903 | 13 | 115
同样地,我在产品使用表中为4种不同的产品(ProductId从1到4)存储了每小时的使用数据。正如你所想象的,它会随着夜间ETL过程将整个前一天的数据转储而不断增长。如果某个产品在一天的任何时间都没有被使用,则该小时的记录不会出现在此表中。同样地,如果某个产品在整个一天中都没有被使用,则该天的记录也不会出现在表中。我需要生成一个报告,提供每日使用情况和最近7天的滚动平均值 -例如:
ProductId | Date | DailyUsage | RollingAverage
1 | 20140901 | sum of usages of that day | (Sum of usages from 20140901 through 20140826) / 7
1 | 20140901 | sum of usages of that day | (Sum of usages from 20140901 through 20140826) / 7
1 | 20140902 | sum of usages of that day | (Sum of usages from 20140902 through 20140827) / 7
2 | 20140902 | sum of usages of that day | (Sum of usages from 20140902 through 20140827) / 7
等等..我计划在SQL Server 2014中创建一个索引视图。您能想到一个高效的SQL查询来实现吗?