How to compare this with this version ?:
SELECT x.* ,(SELECT MAX(Date_Time) FROM dbo.DataTable WHERE Machine_ID = x.Machine_ID AND Date_Time < x.Date_Time ) AS PreviousDateTime FROM dbo.DataTable AS x
Or is this version ?:
SELECT x.* ,triang_join.PreviousDateTime FROM dbo.DataTable AS x INNER JOIN ( SELECT l.Machine_ID, l.Date_Time, MAX(r.Date_Time) AS PreviousDateTime FROM dbo.DataTable AS l LEFT JOIN dbo.DataTable AS r ON l.Machine_ID = r.Machine_ID AND l.Date_Time > r.Date_Time GROUP BY l.Machine_ID, l.Date_Time ) AS triang_join ON triang_join.Machine_ID = x.Machine_ID AND triang_join.Date_Time = x.Date_Time
Both will work better with the Machine_ID, Date_Time index, and to get the right results, I assume this is unique.
You did not mention what is hidden in *, and this can sometimes mean a lot, since the Machine_ID, Date_Time index is usually not distributed, and if you have many columns or they have a lot of data, ...
Cade roux
source share