Simple Moving Average calculation using SQL.


An example of 3-days simple moving average:

select t.d, cast(sum(t1.c)/ COUNT(*) as decimal(10,2)) MA
from tb t 
cross join tb t1
where t1.Id <= t.Id
and  t1.id > t.id - 3
and t.d = getdate() 
group by  t.d 

Table structure: id (consecurive integer), d (date),c (closing price).


theCrunchR | © 2011