Re: Group by date_part

Поиск
Список
Период
Сортировка
От Richard Huxton
Тема Re: Group by date_part
Дата
Msg-id 00bd01c109e7$9056fd80$1001a8c0@archonet.com
обсуждение исходный текст
Ответ на Group by date_part  ("Graham Vickrage" <graham@digitalplanit.com>)
Список pgsql-sql
From: "Roberto Mello" <rmello@cc.usu.edu>

> On Tue, Jul 10, 2001 at 08:04:55PM +0100, Graham Vickrage wrote:
> >
> > The statement I have only selects the count if there is at least 1 order
for
> > a particular day, which make sense.
> >
> > I however need a count of 0 for days that don't have any. Can anyone
help?
> >
> > SQL:
> >
> > SELECT date_part('day', date), count(*)
> > FROM client_order WHERE (date >= '01/05/01' AND date < '01/06/01') AND
> > status = 'Processing'
> > GROUP BY date_part('day', date);
>
> Didn't look very hard, but can't you just add a:
>
> CASE WHEN count(*) > 0 THEN count(*) ELSE 0 END AS count

Don't think so - this one always catches me out, and I have to figure out
how to solve it each time. The problem is that if there aren't any records
with (eg) date = 2001-05-16 then there is simply nothing to return.

I've only ever come up with two solutions:

1. Create a temporary table with all the dates required and a total field
initialized to zero. Update the totals as desired then just read from the
table.

2. Create a temporary table with the dates and join against it. Then you can
use a CASE construct as above to get a zero.

Which one I select depends on usage patterns. If the dates don't change much
(e.g. weekending dates) then I'll use #2, otherwise #1.

I'd be very interested in any clever way of doing this without a temporary
table (or equivalent - if functions could return sets of values you could
use that, but it's basically the same thing).

- Richard Huxton



В списке pgsql-sql по дате отправления:

Предыдущее
От: David Stanaway
Дата:
Сообщение: cumulative sum in aggregate query.
Следующее
От: "Richard Huxton"
Дата:
Сообщение: Re: Problems with PG_DUMP and restore