2017-08-15 61 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