2017-07-19 63 views
1

我有一個包含ID和null startdate的表。我試圖用CTE回填它們。在SQL Server中使用CTE的補餘日期

如果結束日期是 '2011-12-31' 的記錄#1,開始日期爲記錄#2是從記錄#1結束日期+1天即 '2012-01-01'

Create table dbo.input(inputid int null,startDate smalldatetime null,endDate smalldatetime null) 
insert into dbo.input values(111,null,'2011-05-31') 
insert into dbo.input values(111,null,'2012-05-31') 
insert into dbo.input values(111,null,'2013-05-31') 
insert into dbo.input values(111,null,'2014-05-31') 
insert into dbo.input values(111,null,'2015-05-31') 


insert into dbo.input values(222,null,'2010-06-30') 
insert into dbo.input values(222,null,'2011-06-30') 
insert into dbo.input values(222,null,'2012-06-30') 
insert into dbo.input values(222,null,'2013-06-30') 
insert into dbo.input values(222,null,'2014-06-30') 

這是預期的輸出。

Create table dbo.output(outputid int null,startDate smalldatetime null,endDate smalldatetime null) 
insert into dbo.output(111,null,'2011-05-31') 
insert into dbo.output(111,'2011-06-01','2012-05-31') 
insert into dbo.output(111,'2012-05-31','2013-05-31') 
insert into dbo.output(111,'2013-05-31','2014-05-31') 
insert into dbo.output(111,'2014-05-31','2015-05-31') 


insert into dbo.output(222,null,'2010-06-30') 
insert into dbo.output(222,'2010-06-30','2011-06-30') 
insert into dbo.output(222,'2011-06-30','2012-06-30') 
insert into dbo.output(222,'2012-06-30','2013-06-30') 
insert into dbo.output(222,'2013-06-30','2014-06-30') 

這是我試過

WITH CTE AS (
SELECT 
     rn = ROW_NUMBER() OVER (partition by p.inputid ORDER BY p.inputid,endDate), 
     p.inputid 
     ,EndDate 
FROM dbo.input p 
) 
SELECT distinct 
DATEADD(day,1,prev.enddate) as startd,cte.inputid,cte.endDate 
FROM CTE 
LEFT JOIN CTE prev ON prev.rn = CTE.rn - 1 
LEFT JOIN CTE nex ON nex.rn = CTE.rn + 1 
order by cte.inputid,startd 

它不是由inputid分組正確,我不知道如何解決這一問題?

任何幫助表示讚賞。

感謝 MR

回答

1

調整現有查詢,但結果並不完全相同如你所料。 StartDate是否應該是之前EndDate的第二天? (與前一個EndDate不同一天)。

;WITH cte AS (SELECT 
        rn = ROW_NUMBER() OVER (partition by inputid ORDER BY endDate) 
       , * 
      FROM #input 
) 

SELECT a.inputid, DATEADD(DD, 1, b.endDate) as startDate , a.endDate 
FROM CTE a 
LEFT JOIN CTE b 
    ON a.inputid = b.inputid and a.rn = b.rn + 1 
ORDER BY a.inputid, a.startDate; 
0

只要你使用SQL Server 2012或更高版本,可以使用以下...

SELECT 
    i.inputid, 
    startDate = DATEADD(dd, 
         CASE WHEN ROW_NUMBER() OVER (ORDER BY i.inputid, i.endDate) = 2 THEN 1 ELSE 0 END, 
         LAG(i.endDate, 1) OVER (PARTITION BY i.inputid ORDER BY i.endDate) 
         ), 
    i.endDate 
FROM 
    #input i;