Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Hi Experts,I am trying to get the moving average for the past 12 months in a simple fact table. (i.e. July 2010 => averages of past 11 months + current month)I have a period column (200912, 201001, 201002, 201003, etc) and a value coumn containing figures.200912 / 10200912 / 12200912 / 13201001 / 12...etcEnd results that I want to achieve is like thisperiod / Sales / Moving_average200912 / 120 / 118201001 / 150 / 140201002 / 200 / 150etccould you please help,.thanks alotJames
khtan
In (Som, Ni, Yak)
17689 Posts
Posted - 2010-07-02 : 00:47:57
you can use CROSS APPLY to calculate the avg
select *from [simple fact table] t cross apply ( select Moving_average = avg(Sales) from [simple fact table] x where x.period >= convert(varchar(6), dateadd(month, -11, convert(datetime, convert(varchar(10), t.period) + '01')), 112) and x.period <= t.period ) a