X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 8372F474E4F for ; Thu, 3 Apr 2003 16:02:05 -0500 (EST) Received: from localhost.localdomain (unknown [65.217.53.66]) by postgresql.org (Postfix) with ESMTP id 93A0B474E44 for ; Thu, 3 Apr 2003 16:02:04 -0500 (EST) Received: from thorn.mmrd.com (thorn.mmrd.com [172.25.10.100]) by localhost.localdomain (8.12.8/8.12.5) with ESMTP id h33LdAkj019039 for ; Thu, 3 Apr 2003 16:39:10 -0500 Received: from gnvex001.mmrd.com (gnvex001.mmrd.com [192.168.3.55]) by thorn.mmrd.com (8.11.6/8.11.6) with ESMTP id h33L24x13931 for ; Thu, 3 Apr 2003 16:02:05 -0500 Received: from camel.mmrd.com ([172.25.5.213]) by gnvex001.mmrd.com with SMTP (Microsoft Exchange Internet Mail Service Version 5.5.2653.13) id F3HTLZHR; Thu, 3 Apr 2003 16:02:04 -0500 Subject: can i make this sql query more efficiant? From: Robert Treat To: pgsql-sql@postgresql.org Content-Type: text/plain Content-Transfer-Encoding: 7bit X-Mailer: Ximian Evolution 1.0.8 Date: 03 Apr 2003 16:02:04 -0500 Message-Id: <1049403724.13799.5473.camel@camel> Mime-Version: 1.0 X-Spam-Status: No, hits=-12.1 required=5.0 tests=BAYES_10,USER_AGENT_XIMIAN autolearn=ham version=2.50 X-Spam-Level: X-Spam-Checker-Version: SpamAssassin 2.50 (1.173-2003-02-20-exp) X-Archive-Number: 200304/52 X-Sequence-Number: 12753 create table baz (event text, level int); insert into baz values ('x',1); insert into baz values ('x',2); insert into baz values ('x',3); insert into baz values ('y',2); insert into baz values ('y',3); insert into baz values ('y',3); select * from baz; event | level -------+------- x | 1 x | 2 x | 3 y | 2 y | 3 y | 3 (6 rows) I want to know how many ones, twos, and threes there are for each event: select event, (select count(*) from baz a where level = 1 and a.event=baz.event) as ones, (select count(*) from baz a where level = 2 and a.event=baz.event) as twos, (select count(*) from baz a where level = 3 and a.event=baz.event) as threes from baz group by event; which gives me: event | ones | twos | threes -------+------+------+-------- x | 1 | 1 | 1 y | 0 | 1 | 2 (2 rows) which is fine, but I am wondering if there is a better way to do this? I'd mainly like to reduce the number of subqueries involved. Another improvement would be to not have to explicitly query for each level, though this isn't as big since I know the range of levels in advance (famous last words for a dba :-) Thanks in advance, Robert Treat