如何在PostgreSQL中找到两个整数系列之间的重叠?

时间:2016-12-27 12:20:50

标签: sql postgresql

我有两列如下:

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=5id=1 and id=4id=6 and id=2

之间存在重叠

我应该注意start总是小于或等于end

如何使用SQL找到这些重叠? 基本上我希望结果是:

1
2
4
5
6

2 个答案:

答案 0 :(得分:1)

使用exists

,您将获得与其他ID重叠的ID
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])
    )