how do I group by by hour in postgresql with a "time" field?
SqlPostgresqlSql Problem Overview
I have a table with a column ctime
of type time without time zone
.
| cdate | ctime
+------------+----------
| 2016-12-24 | 12:02:17
| 2016-12-24 | 12:02:32
| 2016-12-24 | 12:03:00
| 2016-12-24 | 12:02:10
I would like to group by both cdate
and ctime
but would like for ctime
to count only hours.
Sql Solutions
Solution 1 - Sql
use date_trunc
:
group by cdate, date_trunc('hour', ctime)
Solution 2 - Sql
I think date_part('hour', ctime)
is a better choice if you just want to group based on the hour.
date_part('hour', timestamp '2001-02-16 20:38:40') ---> 20
date_trunc('hour', interval '2 days 3 hours 40 minutes') ---> 2 days 03:00:00