查找在Oracle表中只出现一次的ID

igetnqfo  于 2023-10-16  发布在  Oracle
关注(0)|答案(2)|浏览(109)

我需要找到在表中没有历史的数据,在下面给出的输入数据ID 37798411和74368539有历史,我需要用SQL查询过滤掉。我使用了下面的SQL,但没有得到正确的结果集

SELECT
    *
FROM
    data_set
WHERE
    id IN (
    SELECT
        id
    FROM
        data_set
    GROUP BY
        id
    HAVING
        count(id) = 1)

INPUT

ID           Start_date                    End_date
---------------------------------------------------------
37798411    2023-09-21 00:00:00.000 
37798411    2023-04-27 00:00:00.000 2023-09-20 00:00:00.000
37798411    2022-07-21 00:00:00.000 2023-04-26 00:00:00.000
74368539    2023-09-27 00:00:00.000 
74368539    2023-03-30 00:00:00.000 2023-09-26 00:00:00.000
83851566    2023-09-21 00:00:00.000 
83849576    2023-09-21 00:00:00.000 
84042557    2023-09-21 00:00:00.000 

output 

ID           Start_date                    End_date
------------------------------------------------------------
83851566    2023-09-21 00:00:00.000 
83849576    2023-09-21 00:00:00.000 
84042557    2023-09-21 00:00:00.000
7jmck4yq

7jmck4yq1#

你也可以这样做,这将返回一个结果集,* 排除 * 在原始表中有多个条目的记录:

select *
from data_set s
where not exists (
                 select 1 
                 from data_set
                 where id = s.id
                 having count(1) > 1
                 )
2lpgd968

2lpgd9682#

如果支持,可以使用窗口函数count()

SELECT ID,  Start_date, End_date
FROM (
  SELECT *, count(*) over (partition by id) as total
  FROM data_set
) AS S 
WHERE total = 1;

Demo here

相关问题