首页 > 解决方案 > 根据条件分组和删除行

问题描述

我在 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

我无法找到解决此问题的方法。非常感谢任何帮助。谢谢

标签: sqldatabasepostgresqlselect

解决方案


我认为您正在寻找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')
)

DB Fiddle 上的演示

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

推荐阅读