【问题标题】:How to filter out a "NULL" valued line if there's another line that is otherwise identical but doesn't have a "NULL" value?如果有另一行相同但没有“NULL”值,如何过滤掉“NULL”值的行?
【发布时间】:2020-08-18 09:21:51
【问题描述】:

从图片中可以看出。第 5 行和第 6 行在其他方面相同,但第 5 行具有“NULL”值。所以我想过滤掉第 5 行,但留下第 6 行。

还有一些具有“NULL”值的单行,但我也想保留这些。那么我该怎么做呢?如何保留具有“NULL”值的单个/唯一行并同时过滤掉具有相同对应项但对应项具有“NULL”值的行?

我尝试使用 coalesce group by -function 但还没有得到想要的结果。

【问题讨论】:

  • 您使用的是哪种 DBMS 产品? “SQL”只是所有关系数据库都使用的一种查询语言,而不是特定数据库产品的名称。请为您正在使用的数据库产品添加tagWhy should I tag my DBMS
  • 我开始写一个答案,但是当我无法复制列名时退出了......

标签: sql group-by where-clause sql-null


【解决方案1】:

你可以使用not exists:

select t.*
from mytable t
where 
    date_updated is not null
    or not exists (
        select 1
        from mytable t1
        where 
            t1.state = t.state
            and t1.foo = t.foo
            and t1.date_created = t.date_created
            and t1 date_created is not null
    )

另一个选项是窗口函数,如果您的数据库支持它们:

select *
from (
    select  
        t.*,
        max(date_updated) over(partition by state, foo, date_created) max_date_updated
    from mytable t
) t
where date_updated is not null or max_date_updated is null

【讨论】:

    猜你喜欢
    • 2016-09-23
    • 1970-01-01
    • 1970-01-01
    • 2019-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    相关资源
    最近更新 更多