2017-08-15 63 views
0

我正在调整数据库表中的重叠日期。 的样本数据如下无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 

非常感谢您对这个帮助。

+0

您正在使用哪种版本的sql server?你试过什么了? –

+0

使用SQL Server 2008 R2。 – Harry

+0

你有日历桌吗? – justiceorjustus

回答

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

这使用'cte' ... – iamdave

+0

是的只是发现OP是问没有CTE ...更新 –

+0

如果有一行是日期时间完全包含在另一行的时间段内,这项工作是否会工作? – iamdave

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