Search code examples
sqlsql-servert-sqlwindow-functions

Calculate the average of the last 12 months for every month?


I have a SQL server table with values:

 CREATE TABLE [dbo].[MonthleyAvarage](
    [Boxes] [int] NULL,
    [DateMonthly] [date] NULL
) ON [PRIMARY]
GO

insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (1,'01/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (10,'02/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (5,'03/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (9,'04/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (3,'05/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (7,'06/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (5,'07/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (4,'08/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (55,'09/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (6,'10/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (8,'11/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (0,'12/01/2010')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (2,'01/01/2011')
insert into MonthleyAvarage ([Boxes],[DateMonthly]) values (1,'02/01/2011')

enter image description here

I tried to calculate the average of the last 12 months for every month but I only reach this to take the average of the cumulative not just for last 12 months

select AVG(Boxes) over (order by DATEADD(MONTH, DATEDIFF(MONTH, 0, DateMonthly), -12)) as avarage,DateMonthly,Boxes 
from monthleyavarage

How can I just take the last 12 months? To be like this:

enter image description here

How can I make it please?


Solution

  • You can use window functions with the proper window clause:

    select 
        boxes,
        dateMonthly,
        avg(boxes) 
            over(order by dateMonthly rows between 11 preceding and current row) avg_boxes
    from monthleyavarage
    

    This gives you the average of the current month and the 11 preceding.