To start, I've browsed through all similar questions (like this one) but none seem to be quite the same.
I am trying to find the maximum occurrences of an action within a rolling 24 hour period of time. Example data in the table would look like the following:
id | datetime
--------------------------
1 | 2015-03-01 12:01:00
2 | 2015-03-01 12:01:30
3 | 2015-03-01 12:02:42
4 | 2015-03-01 12:05:18
5 | 2015-03-01 12:07:22
6 | 2015-03-02 13:26:59
and so on ...
I want to find the maximum number of items sold within any 24 hour window over a certain interval. I know this SQL won't currently work but gets to the point of what I'm trying to do:
SELECT
date_trunc('hour',i.dateSold AT TIME ZONE 'America/Chicago') AS endHour,
SUM(CASE WHEN i.dateSold >= i.dateSold - INTERVAL '24 HOURS' AND i.dateSold < i.dateSold AT TIME ZONE 'America/Chicago' THEN 1 ELSE 0 END) as itemsSold
FROM items_sold i
WHERE
i.dateSold >= '2015-03-13 00:00:00 America/Chicago'
AND i.dateSold < '2015-03-16 00:00:00 America/Chicago'
GROUP BY
date_trunc('hour',i.dateSold AT TIME ZONE 'America/Chicago')
My thought is, I may need to build a CTE with start and end dates but am having trouble coming up with a workable solution. Any ideas?