Re: Group by range in hour of day

From: Paul Jungwirth <pj(at)illuminatedcomputing(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Re: Group by range in hour of day
Date: 2015-03-17 16:09:29
Message-ID: 550851B9.2000205@illuminatedcomputing.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

>> test=> select h, count(*) from start_end, generate_series(0, 23) as s(h) where h between extract(hour from start_time) and extract(hour from end_time) group by h order by h;
>>
>> h | count
>> ----+-------
>> 8 | 2
>> 9 | 3
>> 10 | 2
>> 11 | 2

Note if you always want all 24 rows with a count of 0 when appropriate
(which seems common in reports with tables or plots), you can just tweak
the above query to use a left join: FROM generate_series(0, 23) AS s(h)
LEFT OUTER JOIN start_end ON h BETWEEN ...

Paul

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message zach cruise 2015-03-17 16:16:53 select from table1 and table3 where (how table1 and table3 are related) is stored in table2?
Previous Message Elena Fernandez Carmona 2015-03-17 15:52:50 Re: compatibilty postgres 9.2 RHEL 6.4