查询到目前为止:
SELECT Month
,Year
,vol
--sum(vol) over (order by month,year ROWS BETWEEN 2 PRECEDING AND current row) sumnetvol,
,AVG(vol) OVER (ORDER BY Month, Year ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) '3monthra'
,name
,cnt
,costx
FROM(SELECT MONTH(CONVERT(DATETIME, CAST(monthnumber AS NVARCHAR(10)) + '01')) AS [Month]
,YEAR(CONVERT(DATETIME, CAST(monthnumber AS NVARCHAR(10)) + '01')) AS [Year]
,SUM(SumOfNetAmount) AS vol
,COUNT(*) AS cnt
,costx
,name
FROM [ngl_OTB]
GROUP BY costx
,MONTH(CONVERT(DATETIME, CAST(monthnumber AS NVARCHAR(10)) + '01'))
,YEAR(CONVERT(DATETIME, CAST(monthnumber AS NVARCHAR(10)) + '01'))
,name
,SumOfNetAmount) s
WHERE costx = '1000.002'
AND name = 'ngl-raw'
ORDER BY Month
,Year
我需要有关如何递归设置[costx]和[name]列的帮助,以允许三个月正确滚动每个[costx]和[name]的平均值。所有尝试都提供了错误的计算方法,例如3个月的平均滚动平均值正在渗入其他costx和名称。我的目标是将所有数据按costx分组,并按年份和月份对名称和顺序进行分组,然后使用该[costx]的[vol]值对每个costx进行平均3个月的平均滚动。