从单个日期列创建开始日期和结束日期

时间:2017-06-08 13:59:36

标签: sql-server

输入:

Id |Status  |Modified_date
-----------------------------------------
1  |active  |20-10-2016   
1  |removed |09-11-2016    
2  |active  |21-10-2016    
2  |removed |11-01-2017

我想将开始日期和结束日期添加为新列,输出应该看起来像

ID       | status   | start_Date  | end_date
-----------------------------------------
1/1/1900 | active   | 20-10-2016  |9/11/2016             
1/1/1900 | removed  | 9/11/2016   |99-99-9999
1/2/1900 | active   | 21-10-2016  |11/1/2017    
1/2/1900 | removed  | 11/1/2017   |99-99-9999

请告诉我这是怎么回事

1 个答案:

答案 0 :(得分:0)

简单OUTER APPLY应该做的事情:

SELECT  c.id,
        c.[status],
        c.[Modified_date] as [start_date],
        COALESCE(t.[Modified_date],'99-99-9999') as end_date --or ISNULL
FROM YourTable c
OUTER APPLY (
    SELECT TOP 1 [Modified_date]
    FROM YourTable 
    WHERE ID = c.ID AND [Modified_date] > c.[Modified_date]
    ) as t

输出:

id          status  start_date end_date
----------- ------- ---------- ----------
1           active  20-10-2016 09-11-2016
1           removed 09-11-2016 99-99-9999
2           active  21-10-2016 11-01-2017
2           removed 11-01-2017 99-99-9999

或使用LEAD(从SQL Server 2012开始):

SELECT  id,
        [status],
        [Modified_date] as [start_date],
        LEAD([Modified_date],1,'99-99-9999') OVER (PARTITION BY Id ORDER BY [Modified_date] DESC) as end_date
FROM YourTable