2011-03-15 102 views
0

我有一個表的數據,像這樣:如何在連續日期的記錄中查找日期範圍?

ID StartDate EndDate  EffectiveDate 
-- --------- -------  ------------- 
1  1/1/2009  12/31/2009 12/31/2009 
1  7/1/2009  12/31/2009 7/1/2009 
1  8/1/2009  12/31/2009 8/1/2009 
2  1/1/2010  12/31/2010 12/31/2010 
2  3/1/2010  12/31/2010 12/31/2010 

我需要一個查詢,將其格式化這個樣子,但是:

ID StartDate EndDate  EffectiveDate 
-- --------- -------  ------------- 
1  1/1/2009  6/30/2009 null 
1  7/1/2009  7/31/2009 7/1/2009 
1  8/1/2009  12/31/2009 8/1/2009 
2  1/1/2010  2/28/2010 null 
2  3/1/2010  12/31/2010 12/31/2010 
... 

它基本上就像分割「點」的時間線,和每個點是具有下一個點的EndDate的新StartDate,依此類推。

我使用CTE,以及下面的查詢嘗試:

SELECT t1.RfqItemOptionId, 
      t1.StartDate, 
      MIN(t2.EffectiveDate) EndDate, 
      t1.EffectiveDate EffectiveDate 
    FROM @OptionPeriods t1 
LEFT JOIN @OptionPeriods t2 ON t1.RfqItemOptionId = t2.RfqItemOptionId 
          AND t1.EffectiveDate < t2.EffectiveDate 
GROUP BY t1.RfqItemOptionId, t1.StartDate, t1.EffectiveDate 

,接近...但沒有雪茄:(

誰能幫助

回答

3
;With Base As 
(
    Select 
      * 
     , ROW_NUMBER() Over (Partition By ID Order By StartDate) RowNum 
    From 
     @OptionPeriods 
) 
Select 
     B1.* 
    , IsNull(B2.StartDate - 1, B1.EndDate) As NewEndDate 
    , Case B1.RowNum When 1 then Null Else B1.StartDate End As NewEffectiveDate 
From 
    Base B1 
Left Join 
    Base B2 
On 
    B1.ID = B2.ID 
    AND 
    B1.RowNum + 1 = B2.RowNum 
+0

完美!謝謝!!! – vinco83

0

我是一個oracle人,這裏是oracle的oracle版本.... 您可以用相應的SQL-Server SQL替換相關的分析SQL ...

SELECT id, 
     startdate, 
     enddate, 
     case WHEN enddate < effectivedate THEN null ELSE effectivedate end AS effectivedate 
FROM (
    SELECT id, 
      startdate, 
      nvl2(next_startdate,(next_startdate-1),enddate) enddate, 
      effectivedate 
    FROM (
     SELECT a.*, 
       lead(startdate,1) over (partition by id order by id,startdate) next_startdate 
     FROM tblTest a 
     ORDER BY 1,2 
    ) 
); 

感謝, Venkat

相關問題