我有两列如下:
start end id
120 125 1
1 13 2
14 17 3
100 121 4
99 100 5
2 6 6
正如您所看到的,id=4 and id=5
,id=1 and id=4
,id=6 and id=2
我应该注意start
总是小于或等于end
。
如何使用SQL找到这些重叠? 基本上我希望结果是:
1
2
4
5
6
答案 0 :(得分:1)
使用exists
:
select id
from t
where exists (select 1
from t t2
where t2.start <= t.end and t2.end >= t.start and t2.id <> t.id
);
我认为看到重叠的ID的对会更有用:
select t.id, t2.id
from t t join
t t2
on t2.start <= t.end and t2.end >= t.start and t.id < t2.id;
编辑:
以下是它的工作演示:
with t (start, "end", id) as (
values (120, 125, 1),
(1, 13, 2),
(14, 17, 3),
(100, 121, 4),
(99, 100, 5),
(2, 6, 6)
)
select id
from t
where exists (select 1
from t t2
where t2.start <= t."end" and t2."end" >= t.start and t.id <> t2.id
);
答案 1 :(得分:0)
select distinct d1.id
--, d2.id id_overlap -- if you want to see the overlapping serie id uncomment this line
from t d1
join t d2 on
(d1.id <> d2.id) and
(
(d1.start between d2.start and d2.[end] or d1.[end] between d2.start and d2.[end])
or
(d2.start between d1.start and d1.[end] or d2.[end] between d1.start and d1.[end])
)