您可以使用超前/滞后在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