2012-03-30 20 views
0

問題在於,SQL需要很長的時間,並且必須有更好的方法。我已經選擇了情景波動的緩慢部分。 場景: 兩個(臨時)表格,其中車輛的開始和結束事件時間必須配對至數字閒置持續時間。問題是一些事件數據丟失。我想出了一個基本的方法來確定最後的結束時間是在下一個開始時間之後,並且刪除無效的開始時間。再次不優雅+很慢。在SQL數據中配對和查找異常的最佳方法

表:

create table #start(VehicleIp int null,           CurrentDate datetime null, 
        EventId int null, 
        StartId int null) 
create table #end(VehicleIp int null, 
     CurrentDate datetime null, 
     EventId int null, 
     EndId int null) 

- //注:StartId和endID所都預先填寫有類似:

ROW_NUMBER() Over(Partition by VehicleIp order by VehicleIp, CurrentDate) 

- //慢SQL

while exists(
      select top 1 tOn.EventId 
      from #start as tOn 
      left JOIN #end tOff 
      on tOn.VehicleIp = tOff.VehicleIp and 
      tOn.StartID = tOff.EndID +1 
    ) 
begin 

     declare @badEntry int 

     select top 1 @badEntry = tOn.EventId 
     from #s as tOn 
      left JOIN #se tOff 
       on tOn.VehicleIp = tOff.VehicleIp and 
       tOn.StartID = tOff.EndID +1 
     order by tOn.CurrentDate 

     delete from #s where EventId = @badEntry 

     ;with _s as (select VehicleIp, CurrentDate, EventId, 
          ROW_NUMBER() Over(Partition by VehicleIp 
          order by VehicleIp, CurrentDate) StartID 
        from #start) 
     update #start 
    set StartId = _s.StartId 
    from #s join _s on #s.EventId = _s.EventId 

end 

回答

1

假設你從一個包含車輛和使用它的區間的表開始,t他的查詢將識別差距。

select b.VehicleID, b.IdleStart, b.IdleEnd 
from 
    (
     select VehicleID, 
     -- If EndDate is not inclusive, remove +1 
      EndDate + 1 IdleStart, 
     -- First date after current for this vehicle 
     -- If you don't want to show unused vehicles to current date remove isnull part 
      isnull((select top 1 StartDate 
       from TableA a 
       where a.VehicleID = b.VehicleID 
       and a.StartDate > b.StartDate 
       order by StartDate 
      ), getdate()) IdleEnd 
     from TableA b 
    ) b 
where b.IdleStart < b.IdleEnd 

如果日期還有時間部分,他們應該被截斷到所需的精度,這裏是天:

dateadd(dd, datediff(dd,0, getDate()), 0) 

替換任何精確度爲HH,MM或DD。

And here is Sql Fiddle with test

相關問題