【问题标题】:Group by and delete rows based on conditions根据条件分组和删除行
【发布时间】:2020-09-06 03:21:01
【问题描述】:

我在 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) 的行,这些行与 'Procedure' 和 'Behavioral' 相关联

1       Procedure        c
3       Behavioral       f

但是,我还想排除与它们关联的其他行

1       Other            a
3       Combination Drug d
3       Drug             g

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

【问题讨论】:

  • 请澄清您的问题。我已经读了几遍了,我不清楚应该包括或排除什么。另外,请始终公开您的 Postgres 版本。

标签: sql database postgresql select


【解决方案1】:

我想你在找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')
)

Demo on 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多