I am trying to calculate, say, a 3-day moving average (actually 30-day) volume for stocks. I am trying to get the average of the last 3 records of the date (and not today - 3 days). I tried to do something with rownumber in SQL Server 2012, but without success. Maybe someone will help. Below is a diagram of the template, and my attempt to garbage in SQL. I have various incarnations below SQL with a group, but still not working. Thank you very much!
select dt_eod, ticker, volume from ( select dt_eod, ticker, avg(volume) row_number() over(partition by dt_eod order by max_close desc) rn from mytable ) src where rn >= 1 and rn <= 3 order by dt_eod
Example circuit:
CREATE TABLE yourtable ([dt_date] int, [ticker] varchar(1), [volume] int); INSERT INTO yourtable ([dt_date], [ticker], [volume]) VALUES (20121201, 'A', 5), (20121201, 'B', 7), (20121201, 'C', 6), (20121202, 'A', 10), (20121202, 'B', 8), (20121202, 'C', 7), (20121203, 'A', 10), (20121203, 'B', 87), (20121203, 'C', 74), (20121204, 'A', 10), (20121204, 'B', 86), (20121204, 'C', 67), (20121205, 'A', 100), (20121205, 'B', 84), (20121205, 'C', 70), (20121206, 'A', 258), (20121206, 'B', 864), (20121206, 'C', 740);