我每小時的產品使用的表(多少次產品使用)的數據 -SQL查詢7天滾動平均值在SQL Server
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)每小時存儲在product_usage表中。正如您可以想象的那樣,隨着夜間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服務器2014年創建索引視圖。你能想到一個高效的SQL查詢來做到這一點嗎?
你稱之爲「滾動平均值」實際上是一個總和。 – 2014-09-18 22:10:00