如何通过加密的hstore键计算组的不同?

时间:2017-01-17 16:36:14

标签: postgresql join count distinct hstore

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

  • count distinct
  • table joins
  • 按hstore键分组

我不认为我太过分了,但是每个组的数量并没有加起来。

Here is the code on rextester.com

到目前为止我所拥有的:

{{1}}

这给了我:

enter image description here

我想要:

enter image description here

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;

http://rextester.com/YVR16306