如何通过加入的 hstore 键在一个组上计数不同?

How to count distinct on a group by hstore key with join?

我正在尝试使用 postgres 执行以下操作:

我不认为我说得太远了,但是 每个组的不同计数不是按值累加的

Here is the code on rextester.com

我目前拥有的:

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 pets.id,locations.attr -> 'country';

这给了我:

而我想要:

失去 GROUP BYpets.id:

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';

编辑:

你真的不需要加入宠物table。此外,使用明确的 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;

http://rextester.com/YVR16306