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

标签 postgresql join count distinct hstore

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

  • 不重复计数
  • 表连接
  • 按 hstore 键分组

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

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

这给了我:

enter image description here

而我想要:

enter image description here

最佳答案

GROUP BY 中丢失 pets.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';

编辑:

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

关于postgresql - 如何通过加入的 hstore 键在一个组上计数不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41702347/

相关文章:

c# - 如何从 PostgreSQL 导出数据库?

postgresql - 将 PostgreSQL 数据库复制到另一个数据库

c# - 单词快速计数

mysql - 需要单个输出行上多行的数据。子查询?

mysql - 能够计算 MySQL 表中重复的行 ID

python - Pandas:为每个唯一的行获取一个新列

postgresql - 用于 postgres 的 liquibase maven 插件生成的 databasechangelog 的插入查询中区分大小写的列名

windows - Postgres 的默认密码是什么

SQL过滤条件在连接条件或where子句中哪个更有效

mysql - 具有多个条件的自连接