简体   繁体   中英

Grouping into interval of 2 hours in Postgres

I have some difficulties with PostgreSQL commands that I want to do.

select code,TIMESTAMP WITHOUT TIME ZONE 'epoch' +
INTERVAL '1 second' * round(extract('epoch' from created_at) / 7200) * 7200 as created_at,COUNT ("active" ) as active
from "otp"
GROUP BY "code", round(extract('epoch' from created_at) / 7200)

This is my data:

code      created_at            active
------    -------------------   ------
467380    2021-08-13 12:03:15   1
656608    2021-08-13 12:22:56   1
892624    2021-08-13 11:59:36   1
868549    2021-08-13 12:10:05   1
804703    2021-08-13 13:04:24   1

I have tried to group them in 2-hour intervals and I get this is my current output:

code      created_at            active 
------    -------------------   ------ 
467380    2021-08-13 12:00:00   1 
656608    2021-08-13 12:00:00   1 
892624    2021-08-13 12:00:00   1 
868549    2021-08-13 12:00:00   1 
804703    2021-08-13 14:00:00   1

but I want to group time between hours 12 to 14 in hours 14, not in hours 12 like:

code      created_at            active 
------    -------------------   ------ 
467380    2021-08-13 14:00:00   1 
656608    2021-08-13 14:00:00   1 
892624    2021-08-13 12:00:00   1 
868549    2021-08-13 14:00:00   1 
804703    2021-08-13 14:00:00   1

how can I achieve it?

I think you need date_bin :

select code,
       date_bin('2 hours', created_at, '2000-01-01 00:00:00') as created_at,
       COUNT ("active" ) as active
from "otp"
GROUP BY "code",
         date_bin('2 hours', created_at, '2000-01-01 00:00:00');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM