How to compute the moving average over the last n hours

前端 未结 2 2030
刺人心
刺人心 2020-12-22 03:36

I am trying to compute efficiently (using SQL Server 2008) the moving average of the ProductCount over a period of 24 hours. For every single row in the Product table, I\'d

2条回答
  •  清酒与你
    2020-12-22 03:49

    Well, the fact that you need to calculate the average for every hour, actually makes this simpler, since you just need to SUM the product count and divide it by a fixed number (24). So I think that this will get the results you want (though in this particular case, a cursor by be actually faster):

    SELECT A.*, B.ProductCount/24 DailyMovingAverage
    FROM ProductInventory A
    OUTER APPLY (   SELECT SUM(ProductCount) ProductCount
                    FROM ProductInventory
                    WHERE ProductName = A.ProductName 
                    AND [Date] BETWEEN DATEADD(HOUR,-23,A.[Date]) AND A.[Date]) B
    

提交回复
热议问题