Search code examples
postgresqljoincountdistincthstore

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


I'm trying to do the following with postgres:

  • count distinct
  • table joins
  • group by hstore key

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:

enter image description here

Whereas I want:

enter image description here


Solution

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

    EDIT:

    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;
    

    http://rextester.com/YVR16306