Re: Group by date_part

From: "Richard Huxton" <dev(at)archonet(dot)com>
To: "Roberto Mello" <rmello(at)cc(dot)usu(dot)edu>, "Graham Vickrage" <graham(at)digitalplanit(dot)com>
Cc: <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Group by date_part
Date: 2001-07-11 08:57:45
Message-ID: 00bd01c109e7$9056fd80$1001a8c0@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

From: "Roberto Mello" <rmello(at)cc(dot)usu(dot)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

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Richard Huxton 2001-07-11 09:06:15 Re: SQL - histogram
Previous Message Richard Huxton 2001-07-11 08:47:33 Re: Problems with PG_DUMP and restore