Re: GROUP BY hour

From: Osvaldo Rosario Kussama <osvaldo(dot)kussama(at)gmail(dot)com>
To: Nathan Thatcher <n8thatcher(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: GROUP BY hour
Date: 2008-08-01 18:23:19
Message-ID: 48935497.2000905@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Nathan Thatcher escreveu:
> I have, what I imagine to be, a fairly simple question. I have a query
> that produces output for a line graph. Each row represents an interval
> on the graph.
>
> SELECT COUNT(call_id) AS value, EXTRACT(hour from start_time) AS hour
> FROM c_call WHERE start_time >= '2008-08-01 00:00:00' AND end_time <=
> '2008-08-01 23:59:59' GROUP BY hour
>
>
> This works great when there is data in each interval but when a given
> interval has no data the group is omitted. What is the best way to
> ensure that the result contains a row for each interval with the value
> field set to zero or null? The reporting tool is incapable of filling
> in the gaps.
>

Try:
SELECT s.hour::int, coalesce(t.value,0) FROM generate_series(0,23) AS
s(hour)
LEFT OUTER JOIN
(SELECT COUNT(call_id) AS value, EXTRACT(hour from start_time) AS hour
FROM c_call WHERE date_trunc('day',start_time) = '2008-08-01'
GROUP BY hour) AS t
ON s.hour = t.hour;

Osvaldo

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Nathan Thatcher 2008-08-01 18:26:29 Re: GROUP BY hour
Previous Message Steve Crawford 2008-08-01 18:18:10 Re: GROUP BY hour