I have the table like below
id timestamp speed
1 11:00:01 100
2 11:05:01 110
3 11:10:01 90
4 11:15 :01 80
I need to calculate moving average like below
id timestamp speed average
1 11:00:01 100 100
2 11:05:01 110 105
3 11:10:01 90 100
4 11:15:01 80 95
What I tried
SELECT
*,
(select avg(speed) from tbl t where tbl.timestamp<=t.timestamp) as avg
FROM
tbl
At first it looks quite easy but when the data on the table swell, it is too slow
Any faster approach?
Your query is one way to do a running average:
The alternative is to use variables:
An index on
tbl(timestamp)
should further improve performance.Or slotting neatly between GL's two answers (performancewise anyway)...
Does MySQL support windowing functions?
If it doesn't this might work, although I doubt it's efficient:
What about a simple concurrent solution?