【问题标题】:how to do lookup and filter data on the same table in Oracle SQL如何在 Oracle SQL 中查找和过滤同一张表上的数据
【发布时间】:2020-06-02 01:21:15
【问题描述】:

在 SQL 中,我们需要从表中过滤掉不必要的数据:

  • 案例 1:如果 2 个 ID 相同且 DOD 不为空,则需要记录

  • 案例 2:如果有单个 id 并且 dod 不为空,则需要记录

  • 案例 3:如果 2 个 id 相同并且其中任何一个的 DOD 为空,则不需要记录

非常感谢您的帮助。

谢谢

【问题讨论】:

    标签: sql oracle window-functions sql-null


    【解决方案1】:

    您可以为此使用分析函数:

    select t.*
    from (
        select 
            t.*, 
            sum(case when dod is null then 1 else 0 end) over(partition by id) no_nulls
        from mytable t
    ) t
    where no_nulls = 0
    

    请注意,这也排除了没有重复 id 但其 dodnull 的记录(您没有描述如何处理这些)。

    您也可以使用not exists(如果需要,可以方便地将其转换为delete 语句):

    select t.*
    from mytable t
    where not exists(select 1 from mytable t1 where t1.id = t.id and t1.dod is null)
    where no_nulls = 0
    

    【讨论】:

      猜你喜欢
      • 2021-10-14
      • 2018-04-06
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 2012-06-03
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多