Ich habe eine Tabelle mit IDs und mit null Startdatum. Ich versuche, sie mit CTE zu füllen.Backfill-Daten mit CTE in SQL Server
Wenn die EndDate sind '2011-12-31' für Datensatz # 1 ist das Startdatum für Datensatz # 2 EndDate von Datensatz # 1 + 1 Tag dh '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')
Dies ist die erwartete Ausgabe.
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')
Das ist, was ich versucht
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
Es ist nicht richtig durch inputid Gruppierung und ich weiß nicht, wie dieses Problem beheben?
Jede Hilfe wird geschätzt.
Dank MR