can i make this sql query more efficiant?

Поиск
Список
Период
Сортировка
От Robert Treat
Тема can i make this sql query more efficiant?
Дата
Msg-id 1049403724.13799.5473.camel@camel
обсуждение исходный текст
Ответы Re: can i make this sql query more efficiant?  (Franco Bruno Borghesi <franco@akyasociados.com.ar>)
Re: can i make this sql query more efficiant?  (Manfred Koizar <mkoi-pg@aon.at>)
Re: can i make this sql query more efficiant?  ("Tomasz Myrta" <jasiek@klaster.net>)
Список pgsql-sql
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     |     1x     |     2x     |     3y     |     2y     |     3y     |     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 |      1y     |    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



В списке pgsql-sql по дате отправления:

Предыдущее
От: "Stefan"
Дата:
Сообщение: PowerBuilder and identity column
Следующее
От: "Dan Langille"
Дата:
Сообщение: Re: PowerBuilder and identity column