【问题标题】:Extract rows where a column has null values group by id按 id 分组提取列具有空值的行
【发布时间】:2020-09-29 14:42:07
【问题描述】:

我在 Postgres 11 中有下表

id          type1   type2                         type3                   code     
NCT00160290 Drug    lactulose                     lactulose               A05BA | A06AD
NCT00160290 Drug    plantago ovata                plantago ovata          (null)
NCT00251238 Drug    ginkgo biloba extract         ginkgo biloba extract   (null)

我想提取所有那些 type3 不为空但代码为空的行,但如果任何 id 有任何 type3 的代码,我应该排除它。

我正在尝试以下查询

select distinct * 
from table
where type3 is not null 
  and code is null   --but this will include 'NCT00160290' which has a code
group by id

想要的输出是:

id          type1   type2                         type3                   code     
NCT00251238 Drug    ginkgo biloba extract         ginkgo biloba extract   (null)

【问题讨论】:

  • 不相关,但是:select distinct * 没有意义。 * 包含主键列,因此永远不会删除任何重复项。
  • 您说您不想在输出中出现'NCT00160290',但它在您想要的结果中,所以您的问题还不清楚。
  • 是的,谢谢你的指出。我更正了。

标签: sql postgresql select subquery window-functions


【解决方案1】:

你可以使用not exists:

select t.*
from mytable t
where 
    t.type3 is not null
    and not exists (
        select 1 
        from mytable t1
        where t1.id = t.id and t1.code is not null
    )

此查询将利用(id, code) 上的索引。

或者,您可以使用窗口函数:

select 
from (
    select t.*, bool_or(code is not null) over(partition by id) has_non_null_code
    from mytable t
) t
where not has_non_null_code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-03
    • 2017-03-25
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-09
    相关资源
    最近更新 更多