WITH summary AS (
	SELECT
		ROW_NUMBER() OVER (
			PARTITION BY l.LogId 
			ORDER BY pl.EndOdometer DESC, pl.[Date] 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.EndOdometer < l.EndOdometer 
				AND pl.[Date] <= l.[Date])
			OR (
				pl.EndOdometer = l.EndOdometer
				AND pl.[Date] < l.[Date]
			)
			OR (
				pl.EndOdometer = l.EndOdometer
				AND pl.[Date] = l.[Date]
				AND pl.Created < l.Created
			))
)
SELECT [Log].LogId, [Log].VehiclePreviousLogId, summary.PreviousLogId
FROM [Log]
	INNER JOIN summary ON [Log].LogId = summary.LogId
WHERE summary.rk = 1
AND [Log].VehiclePreviousLogId != summary.PreviousLogId
