我有以下代码用于计算12个月移动平均线。我想计算每个ACNBR的12个月移动平均值。当只使用一个ACNBR时,代码工作正常,当我尝试计算多个ACNBR的移动平均值时,它不再工作。请协助。谢谢。
- 示例数据代码:
CREATE TABLE #RollingTotalsExample
(
[Date] DATE
,[Value] INT
,[ACNBR] INT
,[CIS] INT
);
INSERT INTO #RollingTotalsExample
SELECT '2011-01-01',626,100,12
UNION ALL SELECT '2011-02-01',231,100,12 UNION ALL SELECT '2011-03-01',572,100,12
UNION ALL SELECT '2011-04-01',775,100,12 UNION ALL SELECT '2011-05-01',660,100,12
UNION ALL SELECT '2011-06-01',662,100,12 UNION ALL SELECT '2011-07-01',541,100,12
UNION ALL SELECT '2011-08-01',849,100,12 UNION ALL SELECT '2011-09-01',632,100,12
UNION ALL SELECT '2011-10-01',906,100,12 UNION ALL SELECT '2011-11-01',961,100,12
UNION ALL SELECT '2011-12-01',361,100,12 UNION ALL SELECT '2012-01-01',461,100,12
UNION ALL SELECT '2012-02-01',928,100,12 UNION ALL SELECT '2012-03-01',855,100,12
UNION ALL SELECT '2012-04-01',605,100,12 UNION ALL SELECT '2012-05-01',83,100,12
UNION ALL SELECT '2012-06-01',44,100,12 UNION ALL SELECT '2012-07-01',382,100,12
UNION ALL SELECT '2012-08-01',862,100,12 UNION ALL SELECT '2012-09-01',549,100,12
UNION ALL SELECT '2012-10-01',632,100,12 UNION ALL SELECT '2012-11-01',2,100,12
UNION ALL SELECT '2012-12-01',26,100,12
UNION ALL SELECT '2011-01-01',626,200,12
UNION ALL SELECT '2011-02-01',231,200,12 UNION ALL SELECT '2011-03-01',572,200,12
UNION ALL SELECT '2011-04-01',775,200,12 UNION ALL SELECT '2011-05-01',660,200,12
UNION ALL SELECT '2011-06-01',662,200,12 UNION ALL SELECT '2011-07-01',541,200,12
UNION ALL SELECT '2011-08-01',849,200,12 UNION ALL SELECT '2011-09-01',632,200,12
UNION ALL SELECT '2011-10-01',906,200,12 UNION ALL SELECT '2011-11-01',961,200,12
UNION ALL SELECT '2011-12-01',361,200,12 UNION ALL SELECT '2012-01-01',461,200,12
UNION ALL SELECT '2012-02-01',928,200,12 UNION ALL SELECT '2012-03-01',855,200,12
UNION ALL SELECT '2012-04-01',605,200,12 UNION ALL SELECT '2012-05-01',83,200,12
UNION ALL SELECT '2012-06-01',44,200,12 UNION ALL SELECT '2012-07-01',382,200,12
UNION ALL SELECT '2012-08-01',862,200,12 UNION ALL SELECT '2012-09-01',549,200,12
UNION ALL SELECT '2012-10-01',632,200,12 UNION ALL SELECT '2012-11-01',2,200,12
UNION ALL SELECT '2012-12-01',26,200,12;
-code
SELECT a.[Date]
,a.ACNBR
,Value=MAX(CASE WHEN a.[Date] = b.[Date] THEN a.Value END)
,Rolling12Months=CASE
WHEN ROW_NUMBER() OVER (ORDER BY a.[Date]) < (12)
THEN NULL
ELSE avg(b.Value)
END
FROM #RollingTotalsExample a
JOIN #RollingTotalsExample b ON b.[Date] BETWEEN DATEADD(month, -11, a.[Date]) AND a.[Date]
GROUP BY a.ACNBR,a.[Date]
ORDER BY a.ACNBR,a.[Date]
答案 0 :(得分:0)
你在看这样的输出吗?
select *, sum(value) over(partition by acnbr order by date rows between 11 preceding and current row) from #RollingTotalsExample
否则发布预期输出