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