我有一個包含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