I have a table of hourly use of the product (how many times the product is used) -
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
Likewise, I have usage data for 4 different products (ProductId 1 to 4) stored for each hour in the product_usage table. As you can imagine, it is constantly growing as the nightly ETL process uploads data for the entire previous day. If the product is not used at any time of the day, a record at that hour will not be displayed in this table. Similarly, if the product is not used throughout the day, the table will not have a record for that day in the table. I need to create a report that gives daily use and the last 7 days of the moving average -
For example:
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
And so on .. I plan to create an indexed view on SQL Server 2014. Can you think of an efficient SQL query for this?
sql sql-server moving-average
Andy t
source share