From: Richard Huxton <dev@archonet.com>
To: Roberto Mello <rmello@cc.usu.edu>
To: Graham Vickrage <graham@digitalplanit.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: Group by date_part
Date: Wed, 11 Jul 2001 09:57:45 +0100
Message-ID: <00bd01c109e7$9056fd80$1001a8c0@archonet.com> (raw)
References: <NDBBJABDILOPAOOMFJHOIEEJCMAA.graham@digitalplanit.com>
<20010710133623.A27302@cc.usu.edu>
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: dev@archonet.com, rmello@cc.usu.edu, graham@digitalplanit.com
Subject: Re: Group by date_part
In-Reply-To: <00bd01c109e7$9056fd80$1001a8c0@archonet.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox