在SQL Oracle中检测有效期内的多个匹配项

时间:2019-07-05 16:25:22

标签: sql oracle join duplicates intervals

我有一个将ID1匹配到ID2的表,其中有两个日期列,用于标识匹配有效的时间间隔。 每个ID1可以有多个ID2,但不能在同一时间间隔。但是,由于数据插补中的错误,表中确实存在这些情况。我必须找出他们。

示例:此表中的最后两个记录存在此问题:2005年至2015年之间,ID1 44与两个不同的ID2的数字22和55相匹配。

ID1     ID2     startdate      enddate
 11      22     2000-01-01  2010-01-01  
 11      33     2010-01-01  9999-01-01  
 44      22     2000-01-01  2010-01-01  
 44      22     2010-01-01  9999-01-01  
 44      55     2005-01-01  2015-01-01  

对于初学者来说,仅具有此问题的不同ID1列表就足够了;如果我还可以识别出所有与约束冲突的记录,那就更好了。

关于在Oracle SQL中执行此操作的最优雅方法的建议?

2 个答案:

答案 0 :(得分:2)

您可以使用exists

select t.*
from t
where exists (select 1
              from t t2
              where t2.id1 = t.id1 and t2.id2 <> t.id2 and
                    t2.startdate < t.enddate and
                    t2.enddate > t.startdate
             )
order by t.id1, t.startdate;

答案 1 :(得分:1)

存在:

select t.*
from tablename t
where exists (
  select 1 from tablename
  where (id1 = t.id1 and id2 <> t.id2) 
    and (
      startdate between t.startdate and t.enddate 
      or
      enddate between t.startdate and t.enddate
      or
      t.startdate between startdate and enddate 
      or
      t.enddate between startdate and enddate
    )   
)