I'm trying to generate rolling averages over set time periods grouped by an item ID column.
Here's the basic layout of the table and some dummy data, with the fluff stripped out:
----------------------------------------------------
| id | itemid | isup | logged |
----------------------------------------------------
| 1 | 1 | true | 2017-03-23 12:55:00 |
| 2 | 1 | false | 2017-03-23 12:57:00 |
| 3 | 1 | true | 2017-03-23 13:07:00 |
| 4 | 1 | false | 2017-03-23 13:09:00 |
| 5 | 1 | true | 2017-03-23 13:50:00 |
| 6 | 2 | false | 2017-03-23 12:55:00 |
| 7 | 2 | true | 2017-03-23 14:00:00 |
| 8 | 2 | false | 2017-03-23 14:03:00 |
----------------------------------------------------
I found an answer to a previous question on rolling averages but I can't quite seem to figure out how to group the averages by the item ID; pretty much all the avenues I've gone down have ended up with the statistics being flat out wrong.
Here's my starting point - I have a feeling that my lack of understanding of ROW_NUMBER() OVER isn't helping matters.
SELECT id, itemid, AVG(isup)
OVER (PARTITION BY groupnr ORDER BY logged) AS averagehour
FROM (
SELECT id, itemid, isup, logged, intervalgroup,
itemid - ROW_NUMBER() OVER (
partition by intervalgroup ORDER BY logged) AS groupnr
FROM (
SELECT id, itemid, logged,
CASE WHEN isup = TRUE THEN 1 ELSE 0 END AS isup,
'epoch'::TIMESTAMP + '3600 seconds'::INTERVAL *
(EXTRACT(EPOCH FROM logged)::INT4 / 3600) AS intervalgroup
FROM uplog
) alias_inner
) alias_outer
ORDER BY logged;
Any help would be much appreciated.