65

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.

6
  • 1
    You can probably do group by cdate, hour(ctime).
    – jarlh
    Feb 8, 2017 at 15:57
  • Please Edit your question and add the expected output based on your sample data. Formatted text please, no screen shots
    – user330315
    Feb 8, 2017 at 15:57
  • @jarlh: I tried that, but it's telling me there's no "hour" function group by cdate, hour(ctime) gives me No function matches the given name and argument types. You might need to add explicit type casts. Feb 8, 2017 at 16:01
  • extract(hour from ctime) is the ANSI SQL way to get the hour part. Perhaps works bettter?
    – jarlh
    Feb 8, 2017 at 16:11
  • @jarlh: there is no hour() function in Postgres
    – user330315
    Feb 8, 2017 at 16:16

2 Answers 2

103

use date_trunc:

group by cdate, date_trunc('hour', ctime)

0
42

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
1
  • 13
    The major difference, which should be highlighted in this answer, is that date_part('hour', ctime) will not differentiate between 4:20 today and 4:20 yesterday (yielding 4 for both), whereas date_trunc('hour', ctime) will (yielding the full original timestamp just with units smaller than an hour truncated away).
    – basse
    Oct 1, 2021 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.