我正在努力调整数据库表中的重叠日期。 示例数据如下
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
感谢您对此的帮助。
答案 0 :(得分:0)
您可以在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
答案 1 :(得分:0)
对@ 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