X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id 15A5B9F9AD3 for ; Wed, 3 May 2006 11:42:32 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 56752-02 for ; Wed, 3 May 2006 11:42:25 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from wolff.to (wolff.to [66.93.197.194]) by postgresql.org (Postfix) with SMTP id E1C6F9F96B6 for ; Wed, 3 May 2006 11:42:24 -0300 (ADT) Received: (qmail 5521 invoked by uid 500); 3 May 2006 14:43:03 -0000 Date: Wed, 3 May 2006 09:43:03 -0500 From: Bruno Wolff III To: ed.temp.01@gmail.com Cc: pgsql-sql@postgresql.org Subject: Re: selects on differing subsets of a query Message-ID: <20060503144303.GB3774@wolff.to> Mail-Followup-To: Bruno Wolff III , ed.temp.01@gmail.com, pgsql-sql@postgresql.org References: <306f0afd0605030147i598ba049q9ef55a3f3b08847c@mail.gmail.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <306f0afd0605030147i598ba049q9ef55a3f3b08847c@mail.gmail.com> User-Agent: Mutt/1.4.2.1i X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200605/42 X-Sequence-Number: 25073 On Wed, May 03, 2006 at 09:47:49 +0100, ed.temp.01@gmail.com wrote: > First post, be gentle as I have terminology problems and so the > subject might be wrongly worded. > > Say I have a table with fields > ... > gender > diet_pref > ... > > What I am trying to construct is a *single* query showing the total > number of males in the table > and also the total number of male vegetarians in the table, i.e. the > 2nd value is computed on a subset of the records needed for the first > value. There are a few ways you could do this. One is to use a CASE function to return 1 for diet_pref = 'veg' and 0 otherwise. Then you can do a count(*) and a count of the CASE result in the same query and get both totals with one pass through the table. Another option would be joining the two queries. I don't think this is a good idea when you have to count everyone anyway, but if you were counting a couple of small subsets of the data and had partial indexes to speed those counts up, this might be a better strategy.