不知道你的愿望格式的输出。这是一种方法来做到这一点。
alter session set nls_date_format = 'dd/mm/yyyy';
with
test_data (period_no, from_dt, to_dt) as (
select 9891, to_date('01/06/2016'), to_date('31/07/2016') from dual union all
select 9892, to_date('01/08/2016'), to_date('30/09/2016') from dual union all
select 9893, to_date('01/09/2016'), to_date('31/10/2016') from dual union all
select 9894, to_date('01/11/2016'), to_date('31/12/2016') from dual union all
select 9895, to_date('15/12/2016'), to_date('28/02/2017') from dual union all
select 9896, to_date('01/03/2017'), to_date('31/05/2017') from dual
)
-- End of simulated table (for testing purposes only, not part of the solution).
-- SQL query begins BELOW THIS LINE.
select a.period_no as period_a, a.from_dt as from_dt_a, a.to_dt as to_dt_a,
b.period_no as period_b, b.from_dt as from_dt_b, b.to_dt as to_dt_b
from test_data a
join
test_data b
on a.period_no < b.period_no
and a.to_dt >= b.from_dt
and b.to_dt >= a.from_dt
;
PERIOD_A FROM_DT_A TO_DT_A PERIOD_B FROM_DT_B TO_DT_B
---------- ---------- ---------- ---------- ---------- ----------
9892 01/08/2016 30/09/2016 9893 01/09/2016 31/10/2016
9894 01/11/2016 31/12/2016 9895 15/12/2016 28/02/2017
我们同表本身,因为我们要比较不同行(在同一个表,而不是在不同的表,但概念是相同的 - 对于这样的比较,你加入的表,即使它是同一张表的两个副本)。这就是所谓的“自我加入”。
然后:有两种方法,其中时间间隔可以不重叠:第二个开始之前的第一个端部,或第一个开始之前,第二个结束。现在NEGATE这个条件(记住“或”的否定是“和”),并在JOIN子句中得到两个额外的条件。
请参阅[我的博客文章](http://tonyandrews.blogspot.co.uk/search/label/overlap) –
FROM_DATE和TO_DATE是'date'数据类型吗? (他们应该是!) – mathguy
@TonyAndrews请检查您刚刚发布的链接。它不适合我。 – mathguy