2013-07-30 108 views
0

我需要間隔過度幫助。我在一個表中的這些記錄(和更多):時間間隔重疊 - teradata

實施例1:

Id---------StartDate------EndDate 

794122 2011-05-10 2999-12-31 

794122 2011-04-15 2999-12-31 

794122 2008-04-03 2999-12-31 

794122 2008-03-31 2999-12-31 

794122 2008-02-29 2999-12-31 

794122 2008-02-04 2999-12-31 

794122 2007-10-10 2999-12-31 

794122 2007-09-15 2999-12-31 

實施例2:

Id---------StartDate------EndDate 

5448 2012-12-28  2999-12-31 

5448 2011-06-30  2999-12-31 

5448 2005-12-26  2011-06-30 

5448 2005-06-15  2011-06-30 

5448 2006-07-31  2006-12-31 

5448 2001-03-31  2006-07-15 

實施例3:

Id---------StartDate------EndDate 

214577 2007-02-28 2999-12-31 

214577 2003-06-20 2007-03-04 

214577 2003-06-20 2007-02-28 

例4:

Id---------StartDate-------EndDate 

9999 2008-05-28  2999-01-01 

9999 2005-03-03  2008-05-31 

9999 2005-05-31  2005-12-31 

9999 2003-12-01  2005-08-12 

9999 2001-01-01  2002-03-05 

9999 2000-01-08  2002-01-01 

我想獲得:

*Example1* - 2007-09-15->3000-01-01 

*Example2* - 2001-03-31->3000-01-01 

*Example3* - 2003-06-20->3000-01-01 

*Example4* - 2003-12-01->3000-01-01 

你有什麼建議,我該怎麼辦呢?因爲我不選擇最大值和最小值(按ID分組) - >這個問題在示例4中。

謝謝!

+0

什麼是你的問題?你能展示你想要的結果嗎? –

+0

我想獲得這些區間: 例1 - 2007-09-15-> 3000-01-01 例題 - 2001-03-31-> 3000-01-01 示例3 - 2003-06- 20-> 3000-01-01 例4 - 2003-12-01-> 3000-01-01 !!! – user2015219

+0

這是一個錯誤文檔嗎? {9999,2008-05-28,2999-01-01} –

回答

0

你只是想做到這一點?

select id, min(start_date) as start_date, max(end_date) as end_date 
from t 
group by id; 

編輯:

現在我明白你需要什麼。它標識開始新週期的行(使用not exists子句查找重疊)。然後,選擇那些行每個ID中的最大start_date

select t.id, min(t.start_date) as start_date, max(t.end_date) as end_date 
from (select id, max(start_date) as maxsd 
     from t 
     where not exists (select 1 
         from t t2 
         where t2.start_date < t.start_date and 
           t2.end_date >= t.start_date 
         ) 
     group by id 
    ) ids join 
    t 
    on t.id = ids.id and 
     t.start_date >= maxsd 
group by t.id; 

的最後一步加入回原來的數據,但該開始日期後開始的任何東西聚集。

+0

謝謝,但它不是在示例4(我需要2003-12-01-> 3000-01-01)工作 – user2015219

0

你想結束日期是下一年的第一天?

select id, min(startdate) start_date, 
     cast(max(extract(year from enddate)) + 1 || '-01-01' as date) end_date 
from table1 
group by id 
+0

謝謝,但我想不間斷的間隔。我總是從max enddate開始並搜索它。 – user2015219

2

例如#4的結果與您的數據不符,應該不是9999,2999-01-02而不是3000-01-01?

用於組合重疊週期的典型解決方案使用嵌套OLAP的功能,爲您的具體要求(僅最近一段時期),它可以是一個有點簡化爲:

SELECT * 
FROM 
(
    SELECT DISTINCT -- DISTINCT is not neccessary, but results in a better plan 
     Id, 
     StartDate, 
     MAX(EndDate) 
     OVER (PARTITION BY Id) + 1 AS EndDate 
    FROM dropme AS t 
    QUALIFY -- find the gap 
     COALESCE(StartDate 
       - MAX(EndDate) 
       OVER (PARTITION BY Id 
         ORDER BY StartDate, EndDate 
         ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), 1) > 0 
) AS dt 
QUALIFY 
    ROW_NUMBER() 
    OVER (PARTITION BY Id 
     ORDER BY StartDate DESC) = 1 
;