Question

How do you create a Moving Average Method in SQL?

order table:

id_order id_staff date_order
O0001   S0003   12/12/2555
O0002   S0003   12/12/2555
O0003   S0003   12/12/2555
O0004   S0003   13/12/2555
O0005   S0003   13/12/2555
O0006   S0003   13/12/2555
O0007   S0003   13/12/2555
O0008   S0003   13/12/2555

detail_order table:

idde_order id_order id_material count
M0004   O0003   S0002   3   
M0005   O0003   S0003   5   
M0009   O0003   S0002   3   
M0010   O0003   S0003   5   
M0011   O0003   S0001   3

Desired table join or output:

Date         count  3 day Moving Average
2012-05-01       2
2012-05-02       3
2012-05-03       5          4
2012-05-04       1          3
2012-05-05       2          3
2012-05-06       3          3
2012-05-07       2          3

Theory

Month count   3-Month Moving Average     4-Month Moving Average
January 10       
February12       
March   13       
April   16  (10+12+13)/3=11.67   
May     19  (12+13+16)/3=13.67   (10+12+13+16)/4=12.75 
June    23  (13+16+19)/3=16      (12+13+16+19)/4=15
July    26  (16+19+23)/3=19.33   (13+16+19+23)/4=17.75
August      (19+23+26)/3=22.67   (16+19+23+26)/4=21 

thank you dear

Was it helpful?

Solution

create table tmp (
  order_date datetime,
  [count] int
)


insert into tmp
  values ('2012-05-01', 2),
         ('2012-05-02', 3),
         ('2012-05-03', 5),
         ('2012-05-04', 1),
         ('2012-05-05', 2),
         ('2012-05-06', 3),
         ('2012-05-07', 2) 
GO

select t.order_date, t.[count], ceiling((t.[count] + t2.[count] + t3.[count]) / 3.0) as moving_average_3day
from (
  select order_date, dateadd(day, -1, order_date) as prev, dateadd(day, -2, order_date) as prev2, [count]
  from tmp
) t
left outer join tmp t2 on t.prev = t2.order_date
left outer join tmp t3 on t.prev2 = t3.order_date
order by 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top