SQL Server 2008 Rolling Average

时间:2015-08-27 20:07:48

标签: sql sql-server-2008

我正在尝试创建一个SQL语句来计算我的数据的6个月滚动平均值。我正在遵循本指南:

SQL Query for 7 Day Rolling Average in SQL Server

但问题是我使用的是SQL Server 2008,答案是2012年。

select 
    x.*,
    avg(dailyusage) over(partition by productid order by productid, date rows between 6 preceding and current row) as rolling_avg
from 
    (select 
         productid, date, sum(usagecount) as dailyusage
     from tbl
     group by productid, date) x

如果有人能帮助我将其翻译成2008年的条款,我们将不胜感激。

由于

1 个答案:

答案 0 :(得分:1)

您可以尝试使用OUTER APPLY,但它不会有效率:

;WITH CTE AS
(
    SELECT  *,
            ROW_NUMBER() OVER(PARTITION BY productid ORDER BY [date]) RN
    FROM (  SELECT productid, [date], SUM(usagecount) dailyusage
            FROM dbo.YourTable
            GROUP BY productid, [date]
         ) t
)
SELECT TOP 100 *
FROM CTE A
OUTER APPLY(SELECT AVG(dailyusage) rolling_avg
            FROM CTE
            WHERE productid = A.productid
            AND A.RN - RN BETWEEN 0 AND 6) B;