Let's just say I have two columns, DATE and VALUE. The dates are not necessarily regularly spaced intervals. How can I create a moving average on VALUE over the past N days? I'm using postgres but mysql solutions would also be helpful.
Data:
DATE VALUE
2012-11-05 10
2012-10-29 31
2012-10-22 108
2012-10-17 3654
2012-10-16 1187
2012-10-15 12033
2012-10-09 41
2012-10-01 85
2012-09-25 20
2012-09-24 285
2012-09-17 20
2012-09-10 20
2012-09-04 41
2012-08-27 63
2012-08-20 52
2012-08-13 160
To do so, we calculate the average of the stock prices from three consecutive days—the day in question and the two previous days—then repeat the same for each day in the data set. This is a three-day moving average, because we average over a period of three days.
The SQL AVG function calculates the average of a series of values that you provide to it. Most of the time, this will be a particular column that you specify, so the average will be all of the values in that column. Just like the MIN and MAX functions, the AVG function is a SQL standard column.
The MySQL example below covers a sliding 7-day window:
select t1.`DATE`, AVG(t2.`VALUE`) as MV_AVG
from MyTable t1
left outer join MyTable t2
on t2.`DATE` between DATE_ADD(t1.`DATE`, INTERVAL -6 DAY)
and t1.`DATE`
group by t1.`DATE`
SQL Fiddle Example
Output:
| DATE | MV_AVG |
------------------------------------------------
| August, 12 2012 20:00:00+0000 | 160 |
| August, 19 2012 20:00:00+0000 | 52 |
| August, 26 2012 20:00:00+0000 | 63 |
| September, 03 2012 20:00:00+0000 | 41 |
| September, 09 2012 20:00:00+0000 | 30.5 |
| September, 16 2012 20:00:00+0000 | 20 |
| September, 23 2012 20:00:00+0000 | 285 |
| September, 24 2012 20:00:00+0000 | 152.5 |
| September, 30 2012 20:00:00+0000 | 52.5 |
| October, 08 2012 20:00:00+0000 | 41 |
| October, 14 2012 20:00:00+0000 | 6037 |
| October, 15 2012 20:00:00+0000 | 6610 |
| October, 16 2012 20:00:00+0000 | 5624.6667 |
| October, 21 2012 20:00:00+0000 | 1649.6667 |
| October, 28 2012 20:00:00+0000 | 31 |
| November, 04 2012 19:00:00+0000 | 10 |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With