在一个查询中为两个联接选择两个计数

时间:2010-10-29 12:36:57

标签: select count postgresql

create table Autorzy(ID int, imie varchar, nazwisko varchar);
create table Wydawnictwa(ID int, nazwa varchar, adres varchar, tel varchar);
create table Ksiazki(ID int, ISBN bigint, wydawnictwo_id int, data date, ilosc int, tytul varchar);
create table KsiazkaAutor(ID int, autor_id int, ksiazka_id int);
create table Recenzje (id int, tresc varchar, autor_id int, ksiazka_id int);

我能做到:

select a.imie, a.nazwisko, count(ka.id) as IloscKsiazek
from autorzy a
left join KsiazkaAutor ka on a.id=ka.autor_id
group by a.imie, a.nazwisko;

从KsiazkaAutor选择计数

select a.imie, a.nazwisko, count(r.id) as IloscRecenzji
from autorzy a
left join Recenzje r on a.id=r.autor_id
group by a.imie, a.nazwisko;

从Recenzje选择计数。

如何在一个SELECT中获得两个计数?

编辑: 第一选:

“博莱斯瓦夫”; “普鲁斯”; 3
“亚当”; “科瓦尔斯基”; 5个
“泉”, “王”; 3个
“安杰伊”; “Sapkowski”; 3个
“瓦迪斯瓦夫”; “雷蒙特”; 3个
“理查德”, “道金斯”; 3个
“苏菲雅”; “Nałkowska”; 3个
“亨里克”; “显克微支”; 3个
“特里”;“普拉切特”; 3
“伊丽莎”; “Orzeszkowa”; 4个
“亚当”; “密坎凯维奇”; 2个
“John R. R。”;“Tolkien”; 5
“Mikołaj”; “哥白尼”; 1个
“LEN”; “Śmierdzący” 0
“简”, “诺瓦克”; 5个
“卡米尔”; “Kowalik” 0
“Ignacy”;“Krasicki”; 3

第二次选择:

“博莱斯瓦夫”; “普鲁斯” 0
“亚当”; “科瓦尔斯基” 0
“泉”, “王”; 0
“安杰伊”; “Sapkowski” 0
“瓦迪斯瓦夫”; “雷蒙特” 0
“理查德”,“道金斯的” 0
“苏菲雅”; “Nałkowska” 0
“亨里克”; “显克微支”; 1个
“特里”;“普拉切特”; 0
“伊丽莎”; “Orzeszkowa”; 2个
“亚当”; “密坎凯维奇” 0
“John R. R。”;“Tolkien”; 0
“Mikołaj”; “哥白尼” 0
“LEN”; “Śmierdzący” 0
“简”,“诺瓦克” 0
“卡米尔”; “Kowalik” 0
“Ignacy”;“Krasicki”; 0

你的回答:

“博莱斯瓦夫”; “普鲁斯”; 3; 0
“亚当”; “科瓦尔斯基”; 5; 0
“泉”, “王”; 3; 0
“安杰伊”; “Sapkowski”; 3; 0
“瓦迪斯瓦夫”; “雷蒙特”; 3; 0
“理查德”; “道金斯”; 3; 0
“苏菲雅”; “Nałkowska”; 3; 0
“亨里克”; “显克微支”; 3; 3个
“特里”;“普拉切特”; 3; 0
“伊丽莎”; “Orzeszkowa”; 8; 8个
“亚当”; “密坎凯维奇”; 2; 0
“John R. R。”;“Tolkien”; 5; 0
“Mikołaj”; “哥白尼”; 1; 0
“LEN”; “Śmierdzący”; 0; 0
“简”; “诺瓦克”; 5; 0
“卡米尔”; “Kowalik”; 0; 0
“Ignacy”;“Krasicki”; 3; 0

1 个答案:

答案 0 :(得分:4)

是的,你可以这样做:

select a.imie, a.nazwisko, 
count(ka.id) as IloscKsiazek1,
count(r.id) as IloscKsiazek2
from autorzy a
left join KsiazkaAutor ka on a.id=ka.autor_id
left join Recenzje r on a.id=r.autor_id
group by a.imie, a.nazwisko;

您还可以在distinct子句中尝试使用count关键字:

select a.imie, a.nazwisko, 
count(distinct ka.id) as IloscKsiazek1,
count(distinct r.id) as IloscKsiazek2
from autorzy a
left join KsiazkaAutor ka on a.id=ka.autor_id
left join Recenzje r on a.id=r.autor_id
group by a.imie, a.nazwisko;