Re: can i make this sql query more efficiant?

From: Manfred Koizar <mkoi-pg(at)aon(dot)at>
To: Robert Treat <xzilla(at)users(dot)sourceforge(dot)net>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: can i make this sql query more efficiant?
Date: 2003-04-03 23:13:18
Message-ID: 2afp8vsf99lhrrtr411ncivnr577s1v394@4ax.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-performance pgsql-sql

On 03 Apr 2003 16:02:04 -0500, Robert Treat
<xzilla(at)users(dot)sourceforge(dot)net> 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

In response to

Browse pgsql-performance by date

  From Date Subject
Next Message Jeffrey D. Brower 2003-04-04 02:43:27 Re: [HACKERS] OSS database needed for testing
Previous Message Josh Berkus 2003-04-03 23:12:45 Re: ext3 filesystem / linux 7.3

Browse pgsql-sql by date

  From Date Subject
Next Message James Taylor 2003-04-04 00:29:08 More wacky grouping
Previous Message Tomasz Myrta 2003-04-03 23:02:09 Re: can i make this sql query more efficiant?