对于我的sql server项目,我必须实现一个查询以获取12个月的累积平均数(YTD问题)。我的代码显示了如何获取AVG_201801,avg_201802,AVG_201803,...,avg_201912。例如:AVG_201801 =(201712 + 201801)/ 2
我已经尽力了,但是我不知道如何获得年初至今的累计数字。预先感谢。
对于结果
Cum_201801=AVG_201801
Cum_201802= (AVG_201801+AVG_201802)/2
Cum_201803=(AVG_201801+AVG_201802+AVG_201803)/3
.....
Cum_201812=(AVG_201801+AVG_201802+AVG_201803+...+AVG_201812)/12
delete from [Forecast].[Forecast_Budget_personnel]
where Measure='avg_month'
and Scenario='2017 6+6'
and Version='Working Version'
INSERT INTO [Forecast].[Forecast_Budget_personnel]
([Heads]
,[Measure]
,[Year_Month]
,[Cost_center]
,[Direct_Indirect]
,[Scenario]
,[Version]
,[Business_categories]
,[Value]
)
select Cur.Heads,
'avg_month',
Cur.Year_Month,
Cur.Cost_center,
Cur.Direct_Indirect,
Cur.Scenario,
Cur.Version,
Cur.Business_categories,
(isnull(Cur.Value,0)+isnull(Upr.Value,0))/2 Value
from [Forecast].[Forecast_Budget_personnel] Cur
left join [Forecast].[Forecast_Budget_personnel] Upr
on Cur.Heads=Upr.Heads
and Cur.Measure=Upr.Measure
and Cur.Cost_Center=Upr.Cost_center
and Cur.Scenario=Upr.Scenario
and Cur.Version=Upr.Version
and Cur.Year_Month-1=Upr.Year_Month