22 lines
1.1 KiB
SQL
22 lines
1.1 KiB
SQL
WITH summary AS (
|
|
SELECT
|
|
ROW_NUMBER() OVER (PARTITION BY l.LogId ORDER BY l.LogId ASC, pl.EndOdometer DESC, pl.Created DESC) AS rk,
|
|
l.LogId, pl.LogId as PreviousLogId
|
|
FROM
|
|
[Log] as l,
|
|
[Log] as pl
|
|
WHERE
|
|
pl.VehicleId = l.VehicleId
|
|
AND ((pl.[Date] <= l.[Date]
|
|
AND pl.EndOdometer < l.EndOdometer)
|
|
OR (
|
|
pl.EndOdometer < l.EndOdometer
|
|
AND pl.Created < l.Created
|
|
))
|
|
)
|
|
UPDATE [Log]
|
|
SET [Log].VehiclePreviousLogId = summary.PreviousLogId
|
|
FROM summary
|
|
WHERE summary.rk = 1
|
|
AND [Log].LogId = summary.LogId
|