I'm trying to do the following with postgres:
I don't think I'm too far, but the count distinct isn't added up per group by values.
Here is the code on rextester.com
What I have so far:
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';
Which gives me:
Whereas I want:
Lose the pets.id
from 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';
You don't really need to join the pets table. Also, use explicit JOIN syntax:
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';
Without using 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;