postgresql - 是否有类似 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 中至少有一个空值和一个非空值。
所以预期的结果是a
,c
因为这些是唯一具有至少一个空值和一个非空值的键
请注意,我在这里没有唯一的主键,所以我不能真正基于 foo 对表进行多次连接并检查每个连接或其他内容。
有谁知道如何解决这个问题?
任何信息将不胜感激。
解决方案
一种解决方案是使用两个 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;
第一个可能更快
推荐阅读
- mysql - 如何比较逗号分隔的字段与mysql中的列?
- angular - Typescript - 未捕获的 DOMException:无法在“HTMLCanvasElement”上执行“toDataURL”:可能无法导出受污染的画布
- ms-access-2016 - 我正在尝试使用组合框链接子表单,我编写了以下代码
- c# - 如何在 Nsubsitute 中使用内部服务?
- javascript - 如何代理静态文件?
- config - U-Boot defconfig 常用配置
- c# - 队列触发 Azure 函数:队列消息处理多次
- python - 无法在 Jupyter Notebook (Python 3.6) 中导入模块
- python - 我可以设置默认的 alexa 插槽值吗?
- sql - 数据库更改时:代码优先模式,代码从 EDMX 文件生成,用于数据库优先