如何从SQL Server中的一个日期获取日期范围开始日期

时间:2016-07-14 07:20:48

标签: sql sql-server

我只有一个日期fromdate,我希望FromdateTodate来自数据。

这是我的表数据:

Name            FromDate
---------------------------------------
Spisak, Gregory 2015-11-11 20:30:00.000
Patel, Tejal    2015-11-12 00:50:00.000
George, Legy    2015-11-12 03:52:00.000
Gorny,Alexander 2015-11-12 10:05:00.000
Weiner, Doron   2015-11-12 10:31:00.000
Bajaj, Jimmy    2015-11-12 12:24:00.000
Lee, Richard    2015-11-14 10:00:00.000
Soria, Alfie    2015-11-14 11:15:00.000
Weiner, Moshe   2015-11-16 09:37:00.000
Kariolis,Ioannis2015-11-17 12:15:00.000
Cleary, Tara A  2015-11-17 15:39:00.000

我想要另一个ToDate列,其中我想要下一个名字的日期' s fromdate

例如:

Name            FromDate                ToDate
---------------------------------------------------------------
Spisak, Gregory 2015-11-11 20:30:00.000 2015-11-12 00:50:00.000
Patel, Tejal    2015-11-12 00:50:00.000 2015-11-12 03:52:00.000

2 个答案:

答案 0 :(得分:1)

select *, todt from yourTable t 
outer apply 
(select top 1 FromDate todt from yourTable 
where FromDate>t.FromDate 
order by FromDate)a

答案 1 :(得分:1)

DECLARE @TEMP TABLE ( _Date DATE )


INSERT  INTO @TEMP
        ( [_Date] )
VALUES  ( GETDATE()  -- _Date - date
          )

INSERT  INTO @TEMP
        ( [_Date] )
VALUES  ( DATEADD(DAY, 1, GETDATE())  -- _Date - date
          )

INSERT  INTO @TEMP
        ( [_Date] )
VALUES  ( DATEADD(DAY, 2, GETDATE())  -- _Date - date
          )

INSERT  INTO @TEMP
        ( [_Date] )
VALUES  ( DATEADD(DAY, 3, GETDATE())  -- _Date - date
          )

INSERT  INTO @TEMP
        ( [_Date] )
VALUES  ( DATEADD(DAY, 4, GETDATE())  -- _Date - date
          );

WITH    CTE
          AS ( SELECT   * ,
                        ROW_NUMBER() OVER ( PARTITION BY '' ORDER BY [_Date] ) rn
               FROM     @TEMP
             )
    SELECT  CTE.[_Date] AS 'StartDate' ,
            CTE2.[_Date] AS 'EndDate'
    FROM    CTE
            INNER JOIN CTE AS CTE2 ON CTE2.rn = CTE.rn + 1