如何在 Oracle SQL 中查找和过滤同一张表上的数据

Posted

技术标签:

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

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

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

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

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

非常感谢您的帮助。

谢谢

【问题讨论】:

【参考方案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

【讨论】:

以上是关于如何在 Oracle SQL 中查找和过滤同一张表上的数据的主要内容,如果未能解决你的问题,请参考以下文章

同一张表中的行之间的差异(Oracle SQL)

在oracle中怎么把一张表的数据插入到另一张表中

如何比较同一张表(SQL Server)中的 2 行?

比较同一张表oracle中的数据

oracle中查找某用户执行某张表的操作操作记录

如何在oracle中使用嵌套游标遍历同一张表[关闭]