You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PostgreSQL中按两列分组统计第三列,过滤仅含单值的分组

问题解决:筛选PostgreSQL中对应多个column2值的column1行

你的原查询逻辑不对,所以返回0行。核心问题是外层分组后的count(t.column2) > 0条件完全没意义——内层已经按column1, column2分组,每个外层分组里的column2都是唯一值,count结果肯定是1,而且你的需求是保留column1对应多个column2值的行,原查询根本没做这个判断。

给你两种可行的写法:

方法1:用窗口函数(推荐)

直接在内层查询里计算每个column1对应的column2总数,然后筛选总数大于1的行:

select column1, column2, dCount
from (
    select 
        column1, 
        column2, 
        count(column3) as dCount,
        count(distinct column2) over (partition by column1) as col2_count
    from schema.table
    where column1 != 0
    group by column1, column2
) t
where col2_count > 1;

方法2:先筛选符合条件的column1再关联

先找出拥有多个不同column2的column1,再和原分组结果关联:

select t.column1, t.column2, t.dCount
from (
    select column1, column2, count(column3) as dCount
    from schema.table
    where column1 != 0
    group by column1, column2
) t
join (
    select column1
    from schema.table
    where column1 != 0
    group by column1
    having count(distinct column2) > 1
) filter_t on t.column1 = filter_t.column1;

这两种写法都能帮你跳过C3、C4这类只有单个column2值的column1,只保留对应多个column2的行。

内容的提问来源于stack exchange,提问作者Aijaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:32:12