How to compute the moving average over the last n hours

前端 未结 2 2024
刺人心
刺人心 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:54

    I added to Lamak's answer to include min/max:

    SELECT *
    FROM ProductInventory A
    OUTER APPLY (   
        SELECT 
            SUM(ProductCount) / 24 AS DailyMovingAverage, 
            MAX(ProductCount) AS MaxProductCount,
            CASE COUNT(*) WHEN 24 THEN MIN(ProductCount) ELSE 0 END AS MinProductCount
        FROM ProductInventory
        WHERE ProductName = A.ProductName 
        AND [Date] BETWEEN DATEADD(HOUR, -23, A.[Date]) AND A.[Date]) B
    

    To account for missing records, check that there were indeed 24 records in the last 24 hours before using MIN(ProductCount), and return 0 otherwise.

    Working SQL Fiddle, with a bunch (bushel?) of Oranges added to show the MinProductCount working

提交回复
热议问题