question

MarieB avatar image
MarieB asked

Rolling Average - without cursor

Hi, I need to calculate a 4 week rolling average for a range of part numbers. - Year Week PartNo Qty Rolling_Avg - 2013 1 123456 5 0 - 2013 1 999999 7 0 - 2013 2 123456 4 0 - 2013 2 999999 8 0 - 2013 3 123456 9 0 - 2013 3 999999 10 0 - 2013 4 123456 5 5.75 - 2013 4 999999 7 8 - 2013 5 123456 4 5.5 - 2013 5 999999 8 8.25 Is it possible to do this without using a cursor? Thanks in advance.
sql-server-2008
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

JohnM avatar image
JohnM answered
Yes, you can use a CTE. Jeremiah Peschka just blogged about this. http://www.brentozar.com/archive/2013/02/rolling-averages-in-sql-server/ Hope this helps!
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Thanks so much for your responses. But how do I cater for the different part_numbers? Is a cursor the only way? I want to calculate the 4 week rolling average for each part_number in a table.
0 Likes 0 ·
Hi all, I can see now how it is done in the CTE, thanks so much for your assistance.
0 Likes 0 ·
Pavel Pawlowski avatar image
Pavel Pawlowski answered
There is also a great article on SQL Server Central [Solving the Running Total and Ordinal Rank Problems][1] by @Jeff Moden. Other way is to use the CLR solution which is the fastest one, although it has its pitfails. [SQL Server and fastest running totals using CLR – Updated][2] and [Calculating running total for last X rows – UPDATED][3] [1]: http://www.sqlservercentral.com/articles/T-SQL/68467/ [2]: http://www.pawlowski.cz/2010/09/sql-server-and-fastest-running-totals-using-clr/ [3]: http://www.pawlowski.cz/2010/10/calculating-running-total-for-last-x-rows/
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.