【问题标题】:PostgreSQL count other values of ID that have the same value of other columnPostgreSQL计算其他列具有相同值的ID值
【发布时间】:2019-06-18 12:59:53
【问题描述】:

假设我们有下表存储观察的id 及其address_id。您可以使用以下代码创建表:

drop table if exists schema.pl_address_cnt;
create table schema.pl_address_cnt (
    id serial,
    address_id int);

insert into schema.pl_address_cnt(address_id) values 
(100), (101), (100), (101), (100), (125), (128), (200), (200), (100);

我的任务是计算每个id 有多少其他ids(因此-1)具有相同的address_id。我想出了一个在原始数据集上非常昂贵的解决方案 (explain)。我想知道我的解决方案是否可以以某种方式优化。

with tmp_table as (select address_id
                        , count(distinct id) as id_count
                    from schema.pl_address_cnt
                    group by address_id
)
select id
    , id_count - 1
from schema.pl_address_cnt as pac
left join tmp_table as tt on tt.address_id=pac.address_id;

【问题讨论】:

    标签: postgresql group-by count


    【解决方案1】:

    您可以尝试省略 CTE,并在公共地址但不同 ID 上执行自左连接,然后聚合它。

    SELECT pac1.id,
           count(pac2.id)
           FROM pl_address_cnt pac1
                LEFT JOIN pl_address_cnt pac2
                          ON pac1.address_id = pac2.address_id
                             AND pac1.id <> pac2.id
           GROUP BY pac1.id
           ORDER BY pac1.id;
    

    为了提高性能,您可以尝试使用 (address_id, id)(id) 上的索引。

    【讨论】:

    • 感谢您的评论。虽然我省略了 CTE 并使用您的解决方案 explain analyse 返回原始查询成本的 3 倍 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2013-08-05
    • 2020-06-02
    相关资源
    最近更新 更多