Count total data with time interval in Postgresql

The question:

I have an issue that I want to count total data with 1 hour interval. However start time is 7:30

Time                   Status
2022-03-24 07:36:00,   Fail
2022-03-24 07:59:00,   Pass
2022-03-24 09:32:00,   Pass
2022-03-24 09:41:00,   Pass
2022-03-24 10:02:00,   Fail
2022-03-24 11:02:00,   Pass
2022-03-24 11:22:00,   Fail

You can see that before 8:30 I have 2 data that 1 pass(07:59) and 1 fail(07:36) so I can count it and create data below

Time                Status  Total
2022-03-24 08:30    Pass    1
2022-03-24 08:30    Fail    1
2022-03-24 09:30    Pass    0
2022-03-24 09:30    Fail    0
2022-03-24 10:30    Pass    2
2022-03-24 10:30    Fail    1
2022-03-24 11:30    Pass    1
2022-03-24 11:30    Fail    1

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

It sounds like you want group your datapoints with date_bin, which allows you to specify an origin time and a stride interval to use as an offset.

SELECT
date_bin('1 hour', Time, TIMESTAMP '2022-03-24 07:30:00') as Time,
Status,
count(*) as Total
FROM datapoints
GROUP BY 1, 2
ORDER BY 1, 2 DESC


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment