暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 识别重叠间隔

askTom 2016-08-04
173

问题描述

嗨,团队,

我有一张表,里面有数字的间隔。但是,我的表有重叠的间隔,并且一个数字可以在多个间隔中。
例如,

开始间隔 | 结束间隔
1 | 2
2 | 4
3 | 6
...

数字2可以在 (1-2) 和 (2-4) 两个区间内。数字3也可以是两个区间 (2-4) 和 (3-6),依此类推。
我需要一个查询来识别重叠的间隔。
例如:

间隔 | | 重叠间隔
开始间隔 | 结束间隔 || 开始间隔 | 结束间隔
1 | 2 || 2 | 4
2 | 4 || 3 | 6
...

下面你可以找到我的查询:

with t1 (start_int, end_int) as (select 1 start_int, 2 end_int from dual
                                 union all
                                 select start_int+1 start_int, end_int+2 end_int from t1 where start_int < 20),
     t2 as (select t1.start_int start_int_1, t1.end_int end_int_1, tt.start_int start_int_2, tt.end_int end_int_2
              from t1
             cross join t1 tt
             where t1.start_int <> tt.start_int
               and t1.end_int <> tt.end_int
               and (tt.start_int <= t1.end_int and tt.end_int >= t1.start_int))
select t2.start_int_1, t2.end_int_1,
       t2.start_int_2, t2.end_int_2
  from t2
order by 1,2,3,4


However, my query returns repeated groups. 例如:

间隔 | | 重叠间隔
开始间隔 | 结束间隔 || 开始间隔 | 结束间隔
1 | 2 || 2 | 4
2 | 4 || 1 | 2

2 | 4 || 3 | 6
3 | 6 || 2 | 4
...

我明白为什么我得到重复的组,但我不知道如何删除它们。
你能帮我吗?

谢谢。

专家解答

要排除您已经考虑过的表,请检查一个表的start_int是否严格小于另一个表的start_int:

with t1 (start_int, end_int) as (
  select 1 start_int, 2 end_int from dual
  union all
  select start_int+1 start_int, end_int+2 end_int 
 from t1 where start_int < 4
), t2 as (
  select t1.start_int start_int_1, t1.end_int end_int_1, tt.start_int  start_int_2, tt.end_int end_int_2
 from t1
  cross join t1 tt
  where t1.start_int <> tt.start_int
   and t1.end_int <> tt.end_int
   and (tt.start_int <= t1.end_int and tt.end_int >= t1.start_int)
   and  t1.start_int < tt.start_int
)
select t2.start_int_1, t2.end_int_1,
       t2.start_int_2, t2.end_int_2
  from t2
order by 1,2,3,4;

START_INT_1  END_INT_1  START_INT_2  END_INT_2  
1            2          2            4          
2            4          3            6          
2            4          4            8          
3            6          4            8

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论