2017-06-26 64 views
0

我有一个表约卖出时间信息,现在我需要知道,如果某行是互相重叠。例如:如果用了一段'01 /二千〇十六分之一十二' 到'31/01/2017' 年:我想知道,如果某行重叠例如'15 /二千〇十六分之一十二' 到'28/02/2017' 年。你有什么主意吗?ORACLE - 如何检查从最新到最新的两个日期?

NUMBER(5)  DATE     DATE 
Period No.  from date   to-date 
----------------------------------------- 
9891    01/06/2016   31/07/2016 
9892    01/08/2016   30/09/2016 
9893    01/09/2016   31/10/2016 -- This row is overlapped 
9894    01/11/2016   31/12/2016 
9895    15/12/2016   28/02/2017 -- This row is overlapped 
9896    01/03/2017   31/05/2017 

我知道了逻辑检查一个两个日期之间的日期(WHERE v_date_1 BETWEEN v_date_2和v_date_3),但我不知道如何检查两个日期之间的两个日期!谢谢。

+0

请参阅[我的博客文章](http://tonyandrews.blogspot.co.uk/search/label/overlap) –

+1

FROM_DATE和TO_DATE是'date'数据类型吗? (他们应该是!) – mathguy

+0

@TonyAndrews请检查您刚刚发布的链接。它不适合我。 – mathguy

回答

4

不知道你的愿望格式的输出。这是一种方法来做到这一点。

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子句中得到两个额外的条件。

+0

感谢Mathguy的帮助和解释。它工作正常,现在我明白如何使用它。再次感谢 :) –