【问题标题】:How to count distinct on a group by hstore key with join?如何通过加入的 hstore 键对组进行区分?
【发布时间】:2017-06-01 19:46:18
【问题描述】:

我正在尝试使用 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';

这给了我:

而我想要:

【问题讨论】:

    标签: postgresql join count distinct hstore


    【解决方案1】:

    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

    【讨论】:

    • 确实(累)。由于这很简单,您是否知道如何调整查询以使用更高效的SELECT COUNT(*) FROM (SELECT DISTINCT 而不是SELECT COUNT(DISTINCTstackoverflow.com/questions/11250253/…
    • 漂亮!如果我可能会问,使用显式 JOIN 语法与我所做的相比有什么附加价值?
    • 显式连接更现代,更清晰易懂,而其他语法已有 20 年历史。
    猜你喜欢
    • 2015-11-04
    • 2020-10-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 2018-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多