2016-10-03 41 views
0

我有以下數據與我一起。我想確保任何特定ID的start_date,end_date和這兩個日期之間的時間段與任何其他ID的日期不重疊。Teradata ROWS UNBOUNDED PRECEDING

ID  Start_Date End_Date 
101 01-01-2001 31-01-2001 
102 01-02-2001 28-02-2001 
103 26-02-2001 31-03-2016 
104 15-03-2001 30-04-2001 
105 01-05-2002 31-05-2002 
106 05-12-2002 31-12-2002 
107 15-12-2002 05-01-2003 

要做到這一點,我在下面的查詢創建:

select id,start_date,end_date, 
case 
when 
end_date < max(end_date) over(order by start_date rows unbounded preceding) 
then 'overlapping' 
when 
start_date < max(end_date) over(order by start_date rows unbounded preceding) 
then 'overlapping' 
else 'non-overlapping' 
end as FLAG from table 

我得到以下輸出具有所有標記爲「重疊」,這是不正確的。我認爲,「無界行前」正在當前行也計算: 能否請您讓我知道我錯了:

ID  Start_Date End_Date Flag 
101 01-01-2001 31-01-2001 Overlapping 
102 01-02-2001 28-02-2001 Overlapping 
103 26-02-2001 31-03-2016 Overlapping 
104 15-03-2001 30-04-2001 Overlapping 
105 01-05-2002 31-05-2002 Overlapping 
106 05-12-2002 31-12-2002 Overlapping 
107 15-12-2002 05-01-2003 Overlapping 
+2

當然'行無界preceding'包括當前行,這是一個快捷方式用於'無界前和當前行之間的行'。你能顯示應該返回什麼確切的結果嗎? – dnoeth

+0

你確定ID103進入2016年,而不是2001年? – Beth

回答

1

有幾種方法去這個問題。由於日期範圍重疊可能很麻煩,我會使用Teradata的時代邏輯和自連接:

SELECT 
    * 
FROM 
    table t1 
    INNER JOIN table t2 ON 
     period(t1.start_date, next(t1.end_date)) P_INTERSECT period(t2.start_date, next(t2.end_date)) IS NOT NULL 

將在您的起始和終止日期轉換爲一個時期的數據類型,然後尋找那些相交時期的記錄。結果將成爲兩條記錄,合併成一條記錄,重疊發生。

0

您也可以嘗試在老式的方法,如:

CREATE TABLE db.t 
    (id INT, 
    start_date DATE, 
    end_date DATE); 
INSERT INTO db.t VALUES (101,'2001-01-01','2001-01-31'); 
INSERT INTO db.t VALUES (102,'2001-02-01','2001-02-28'); 
INSERT INTO db.t VALUES (103,'2001-02-26','2001-03-31'); 
INSERT INTO db.t VALUES (104,'2001-03-15','2001-04-30'); 
INSERT INTO db.t VALUES (105,'2002-05-01','2002-05-31'); 
INSERT INTO db.t VALUES (106,'2002-12-05','2002-12-31'); 
INSERT INTO db.t VALUES (107,'2002-12-01','2003-01-05'); 
SELECT 
    t.id, 
    t.start_date, 
    t.end_date, 
    MAX(CASE WHEN o.id IS NULL THEN 'non-overlapping' 
    ELSE 'overlaps with' || o.id END) AS flag 
FROM 
    db.t t LEFT OUTER JOIN 
    db.t o ON 
    t.start_date < o.end_date AND 
    t.end_date >= o.start_date AND 
    t.id <> o.id 
GROUP BY 1,2,3 

回報(手動排序)

id start_date end_date flag 
101 01/01/2001 01/31/2001 non-overlapping 
102 02/01/2001 02/28/2001 overlaps with  103 
103 02/26/2001 03/31/2001 overlaps with  104 
104 03/15/2001 04/30/2001 overlaps with  103 
105 05/01/2002 05/31/2002 non-overlapping 
106 12/05/2002 12/31/2002 overlaps with  107 
107 12/01/2002 01/05/2003 overlaps with  106