繁体   English   中英

如何在具有连续日期的记录中查找日期范围?

[英]How to find date ranges in records with consecutive dates?

我有一个数据表,如下所示:

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
...

这基本上就像是带有分段“点”的时间线,每个点都是一个新的StartDate,下一个点是EndDate,依此类推。

我尝试使用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

哪家很近...但是没有雪茄:(

有人可以帮忙吗?

;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

我是Oracle的人,这是SQL的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM