我正在尝试使用postgres执行以下操作:
我不认为我太过分了,但是每个组的数量并没有加起来。
Here is the code on rextester.com
到目前为止我所拥有的:
{{1}}
这给了我:
我想要:
答案 0 :(得分:1)
从pets.id
:
GROUP BY
SELECT COUNT(DISTINCT pets.id),locations.attr -> 'country' as country
FROM pets,photos,locations
WHERE photos.pet_id = pets.id
AND photos.location_id = locations.id
GROUP BY locations.attr -> 'country';
你真的不需要加入宠物桌。另外,使用显式JOIN语法:
select
l.attr -> 'country' country,
count(distinct p.pet_id)
from photos p
inner join locations l
on p.location_id = l.id
group by l.attr -> 'country';
不使用COUNT(DISTINCT)
:
select
country, count (pet_id)
from (
select
l.attr -> 'country' country,
p.pet_id
from photos p
inner join locations l
on p.location_id = l.id
group by l.attr -> 'country', p.pet_id
) t
group by country;