Re: Possible to do this in one query?

From: "Andrew G(dot) Hammond" <drew(at)xyzzy(dot)dhs(dot)org>
To: John Oakes <john(at)networkproductions(dot)net>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: Possible to do this in one query?
Date: 2002-03-27 14:58:02
Message-ID: 20020327145802.GA7777@xyzzy.dhs.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Tue, Mar 26, 2002 at 01:22:41PM -0500, John Oakes wrote:
> I have a table with a column that contains fail codes. These codes are 1-9.
> I need to get a count of each of the codes. Right now I have separate
> queries:
>
> select count(*) from tablename
> where failcode = '1';
>
> If I use GROUP BY it obviously doesn't get the count for codes that don't
> exist. I need to have 0 returned though so I have a listing of all 9 fail
> codes and their total, even if it is zero. I tried UNION like this:
>
> select count(*) from tablename
> where failcode = '1';
> UNION
> select count(*) from tablename
> where failcode = '2';
>
> etc, but it too excludes the codes that have a count of zero. Right now I
> have resorted to using 9 separate queries. Is there a way to do this with
> one? Thank you!

You need a table of failcodes first:

CREATE TABLE failcodes (
failcode INTEGER PRIMARY KEY,
description TEXT
);

-- populate it:
INSERT INTO failcodes ( 1, 'Attacked by mob of angry kittens' );
-- ...
INSERT INTO failcodes ( 9, 'Wrong phase of moon' );

SELECT coalesce(count, 0) FROM (
SELECT failcode FROM failcodes
NATURAL LEFT OUTER JOIN
SELECT count (*) FROM tablename GROUP BY failcode
);

Or, be a sneaky bastard and add a fake record for each failcode, and
then count(*) - 1. :)

--
Andrew G. Hammond mailto:drew(at)xyzzy(dot)dhs(dot)org http://xyzzy.dhs.org/~drew/
56 2A 54 EF 19 C0 3B 43 72 69 5B E3 69 5B A1 1F 613-389-5481
5CD3 62B0 254B DEB1 86E0 8959 093E F70A B457 84B1
"To blow recursion you must first blow recur" -- me

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Jairo Tcatchenco 2002-03-27 15:01:56 Vacuumdb - the real advantages
Previous Message Torsten Willrich 2002-03-27 12:23:29 Problem how to combine to two tables