我有一个基于过去3个月计算移动平均值的脚本。
是否可以修改此移动平均线以仅显示第4个月的值?或者当我想基于4个月计算时,然后显示第5行的值,依此类推......
所以重点是只有当我有足够的数据进行计算时才能显示那个月的值。
SELECT
[Brand], [month],
CAST(SUM([Volume]) AS INT) AS [Volume (t)],
AVG(CAST(SUM([Volume]) AS INT)) OVER (PARTITION BY [Brand]) AS [Average (t)],
AVG(CAST(SUM([Volume]) AS INT)) OVER (PARTITION BY [Brand] ORDER BY [month] ROWS BETWEEN 3 PRECEDING AND 1 PRECEDING) AS [Moving Average (3)]
FROM
dw_lc_full_aggregated_1
WHERE
[year] = 2016 AND
[month] BETWEEN 1 AND 9 AND
[Navision Source] = 'HU' AND
[Brand] = 'xxxxxxx'
GROUP BY
[Brand], [month]
答案 0 :(得分:0)
谢谢!我解决了以下问题:
SELECT [Brand],
[month],
cast(sum([Volume]) AS INT) as [Volume (t)],
AVG(cast(sum([Volume])AS INT)) OVER (PARTITION BY [Brand]) AS [Average (t)],
CASE WHEN (Row_Number() OVER (ORDER BY [month]))>3
THEN AVG(cast(sum([Volume])AS INT))
OVER (PARTITION BY [Brand] ORDER BY [month] ROWS BETWEEN 3 PRECEDING AND 1 PRECEDING)
ELSE NULL END AS [Moving Average (3)]
............