pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Andrew G. Hammond <drew@xyzzy.dhs.org>
To: John Oakes <john@networkproductions.net>
Cc: pgsql-sql@postgresql.org
Subject: Re: Possible to do this in one query?
Date: Wed, 27 Mar 2002 09:58:02 -0500
Message-ID: <20020327145802.GA7777@xyzzy.dhs.org> (raw)
In-Reply-To: <001301c1d4f3$37bd5160$f8832341@john>
References: <001301c1d4f3$37bd5160$f8832341@john>

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@xyzzy.dhs.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

view thread (3+ messages)

Message-ID: <20020327145802.GA7777@xyzzy.dhs.org>
Permalink:  ../20020327145802.GA7777@xyzzy.dhs.org/
Also on:    postgresql.org/message-id/20020327145802.GA7777@xyzzy.dhs.org

 · 

reply

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: drew@xyzzy.dhs.org, john@networkproductions.net
  Subject: Re: Possible to do this in one query?
  In-Reply-To: <20020327145802.GA7777@xyzzy.dhs.org>

* 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