首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >提取其中一列具有按id分组的空值的行

提取其中一列具有按id分组的空值的行
EN

Stack Overflow用户
提问于 2020-06-10 16:36:08
回答 1查看 28关注 0票数 1

我在Postgres 11中有以下表格

代码语言:javascript
复制
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不为null但代码为null的所有行,但是如果任何id有任何type3的代码,我应该排除它。

我正在尝试以下查询

代码语言:javascript
复制
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

所需的输出为:

代码语言:javascript
复制
id          type1   type2                         type3                   code     
NCT00251238 Drug    ginkgo biloba extract         ginkgo biloba extract   (null)
EN

回答 1

Stack Overflow用户

发布于 2020-06-10 17:38:01

您可以使用not exists

代码语言:javascript
复制
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)上的索引。

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

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62299239

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档