首页 > 解决方案 > 是否有类似 group by 的东西也允许我查询每个组中的各个行?

问题描述

我使用 PostgreSQL 11.4,我想解决以下问题:

假设我有下表:

foo | bar
---------
a     null
a     2
a     8
a     3
b     2
c     null
c     8
c     5
c     2

我想获取 foo 中的所有字段,其中它在 bar 中至少有一个空值和一个非空值。

所以预期的结果是ac因为这些是唯一具有至少一个空值和一个非空值的键

请注意,我在这里没有唯一的主键,所以我不能真正基于 foo 对表进行多次连接并检查每个连接或其他内容。

有谁知道如何解决这个问题?

任何信息将不胜感激。

标签: postgresql

解决方案


一种解决方案是使用两个 EXISTS 条件:

select distinct foo
from the_table t1
where exists (select * 
              from the_table t2
              where t2.bar is null
                and t2.foo = t1.foo)
  and exists (select * 
              from the_table t3
              where t3.bar is not null
                and t3.foo = t1.foo)

另一种选择是按 foo 分组并计算行数:

select foo
from the_table
group by foo
having count(*) filter (where bar is null) > 0
   and count(*) filter (where bar is not null) > 0;

第一个可能更快


推荐阅读