您可以使用超前/滯後在2012+情況下,由於您使用的是2008年,你可以按照以下查詢:
;With cte as (
Select *, RowN = Row_Number() over(partition by Id order by EndDate) from #sampledata
)
Select StartDate = Coalesce (Case when Dateadd(DD, 1, c2.Enddate) = c1.Startdate then c1.Startdate Else c2.Enddate End, c1.StartDate)
,c1.Enddate, c1.Unit, C1.Id
from cte c1 left join cte c2
on c1.RowN = c2.RowN+1
如果你還不想使用CTE如上那麼你可以做分 - 查詢如下:
Select StartDate = Coalesce (Case when Dateadd(DD, 1, c2.Enddate) = c1.Startdate then c1.Startdate Else c2.Enddate End, c1.StartDate)
,c1.Enddate, c1.Unit, C1.Id
from (Select *, RowN = Row_Number() over(partition by Id order by EndDate) from #sampledata) c1
left join (Select *, RowN = Row_Number() over(partition by Id order by EndDate) from #sampledata) c2
on c1.RowN = c2.RowN+1
您正在使用哪種版本的sql server?你試過什麼了? –
使用SQL Server 2008 R2。 – Harry
你有日曆桌嗎? – justiceorjustus