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
相关产品推荐
相关产品推荐

