无CTE调整重叠日期
问题描述:
我正在调整数据库表中的重叠日期。 的样本数据如下无CTE调整重叠日期
StartDate EndDate UNIT ID
2017-06-09 2017-06-22 1A 21
2017-06-09 2017-06-30 1B 21
2017-07-01 2017-07-31 1B 21
预期输出:
StartDate EndDate UNIT ID
2017-06-09 2017-06-22 1A 21
2017-06-22 2017-06-30 1B 21
2017-07-01 2017-07-31 1B 21
非常感谢您对这个帮助。
答
您可以使用超前/滞后在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
答
对@ Kannan的答案稍作修改。
Select StartDate = Coalesce (Case when c1.Startdate <= c2.Enddate
then c2.Enddate
Else c1.Startdate
End,
c1.StartDate)
,c1.Enddate, c1.Unit, C1.Id
from
(Select *, RowN = Row_Number() over(partition by Id order by EndDate)
from #sample) c1
left join
(Select *, RowN = Row_Number() over(partition by Id order by EndDate)
from #sample) c2
on c1.RowN = c2.RowN+1
您正在使用哪种版本的sql server?你试过什么了? –
使用SQL Server 2008 R2。 – Harry
你有日历桌吗? – justiceorjustus