X-Original-To: pgsql-sql@postgresql.org Received: from spampd.localdomain (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 8612B474E44 for ; Thu, 3 Apr 2003 18:13:23 -0500 (EST) Received: from email01.aon.at (WARSL401PIP8.highway.telekom.at [195.3.96.97]) by postgresql.org (Postfix) with SMTP id A0B1E474E42 for ; Thu, 3 Apr 2003 18:13:22 -0500 (EST) Received: (qmail 640924 invoked from network); 3 Apr 2003 23:13:24 -0000 Received: from m169p008.dipool.highway.telekom.at (HELO cantor) ([62.46.11.8]) (envelope-sender ) by qmail1rs.highway.telekom.at (qmail-ldap-1.03) with SMTP for ; 3 Apr 2003 23:13:24 -0000 From: Manfred Koizar To: Robert Treat Cc: pgsql-sql@postgresql.org Subject: Re: can i make this sql query more efficiant? Date: Fri, 04 Apr 2003 01:13:18 +0200 Message-ID: <2afp8vsf99lhrrtr411ncivnr577s1v394@4ax.com> References: <1049403724.13799.5473.camel@camel> In-Reply-To: <1049403724.13799.5473.camel@camel> X-Mailer: Forte Agent 1.8/32.548 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Spam-Status: No, hits=-31.4 required=5.0 tests=BAYES_10,EMAIL_ATTRIBUTION,IN_REP_TO,REFERENCES, REPLY_WITH_QUOTES,USER_AGENT_FORTE 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/56 X-Sequence-Number: 12757 On 03 Apr 2003 16:02:04 -0500, Robert Treat wrote: >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 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. SELECT event, SUM (CASE level WHEN 1 THEN 1 ELSE 0 END) AS ones, SUM (CASE level WHEN 2 THEN 1 ELSE 0 END) AS twos, SUM (CASE level WHEN 3 THEN 1 ELSE 0 END) AS threes FROM baz GROUP BY event; > Another >improvement would be to not have to explicitly query for each level, This might be a case for a clever set returning function, but that's not my realm. Wait for Joe to jump in ;-) Servus Manfred