I have a table, Measures, with columns: timestamp (Unix timestamp), tag, value.
To get a single moving average of say, 15 days, I can do something like:
SELECT tag,avg(value)
FROM measures
WHERE tag='xtr'
AND timestamp<1353304800
AND timestamp>1350622800
GROUP BY tag;
Now I want to get the moving average of the 150 latest rows, but I’m not sure how to query it.
SELECT t, s,avg(bv)
FROM
(SELECT A.timestamp as t,A.tag as ta,A.value as ac, B.timestamp as tb,B.value as bv,
FROM measures
CROSS JOIN measures B
WHERE A.tag='xtr' AND B.tag='xtr'
GROUP BY A.tag) WHERE ROWNUM <= 150;
This is obviously wrong, but I’ve been thinking about it and cant figure it out. Any ideas?
My train of thought is that I need to match each entry with the 150 entries below it and compute the value average for those 150 entries. I’m also pretty sure that there’s probably a better way without a CROSS JOIN, as that would be very slow.
Not entirely clear what your table structure and uniqueness of data is, but this query will give you a true moving average of the previous 150 rows (inclusive of current row) for all timestamps.
If you just need to isolate the most recent 150 rows then base your query on: