sql - 根据条件分组和删除行
问题描述
我在 postgres 中有下表。
col1 col2 col3
1 Other a
2 Drug b
1 Procedure c
3 Combination Drug d
4 Biological e
3 Behavioral f
3 Drug g
5 Drug g
6 Procedure h
我想根据以下条件选择行。
select * from table where col2 in ('Other', 'Drug', 'Combination Drug', 'Biological')
order by col1
这给了我下面的输出。
col1 col2 col3
1 Other a
2 Drug b
3 Combination Drug d
3 Drug g
4 Biological e
5 Drug g
但是上面的过滤器不包括下面的行,并且包括与“程序”和“行为”相关联的 col1 ids (1, 3) 的行
1 Procedure c
3 Behavioral f
但是,我还想排除与它们关联的其他行
1 Other a
3 Combination Drug d
3 Drug g
我无法找到解决此问题的方法。非常感谢任何帮助。谢谢
解决方案
我认为您正在寻找not exists
:
select t.*
from mytable t
where not exists (
select 1
from mytable t1
where t1.col1 = t.col1 and t1.col2 not in ('Other', 'Drug', 'Combination Drug', 'Biological')
)
col1 | col2 | col3 ---: | :--------- | :--- 2 | 药物 | b 4 | 生物 | e 5 | 药物 | G
您还可以使用窗口函数:
select (t.t).*
from (
select
t,
bool_and(col2 in ('Other', 'Drug', 'Combination Drug', 'Biological'))
over(partition by col1) flag
from mytable t
) t
where flag
推荐阅读
- java - 如何测试安全的端点/休息控制器?Java,带有@Secured
- mysql - 如何选择没有重复的行并仅按某些列分区?
- angular - 错误:p 按钮(和 p 密码)不是已知元素
- reactjs - 如何使用状态更新对象数组中的多个项目?
- oracle - Oracle SQL 假脱机
- django - 通过表单添加多个实例
- oauth-2.0 - 无法使用“httr”接收 Deezer 的有效访问令牌
- google-sheets - 如何用谷歌电子表格中的文字描述替换表情符号?
- javascript - 如何在 chrome 扩展中使用 Google 分析跟踪事件?
- python - 根据输入创建表,如果db文件中不存在输入,则创建表,如果存在,则将ID写入其中