This will probably work:DECLARE @sample TABLE ( [TIME] INT , [ID] VARCHAR(5) )INSERT @sampleVALUES (-216, 'AZA') , (215,'AZA') , (56, 'EA') , (-55, 'EA') , (66, 'EA') , (-03, 'AR') , (03, 'AR') , (04, 'AR') , (87, 'AR') , (03, 'OUI') , (-999, 'OP') , (999, 'OP')/*The expected output isTIME | ID66 | EA03 | OUI87 | AR*/DECLARE @range INT = 1SELECT * FROM @sample; WITH uqSample AS ( SELECT ROW_NUMBER() OVER ( ORDER BY [ID] ) AS [uk] , [TIME] , [ID] FROM @sample )SELECT s1.[TIME], s1.[ID]FROM uqSample AS s1WHERE NOT EXISTS ( SELECT 1 FROM uqSample AS s2 WHERE s2.[ID] = s1.[ID] AND s2.[uk] <> s1.[uk] AND ABS(ABS(s2.[TIME]) - ABS(s1.[TIME])) <= @range )
But it will be slow.There is no unique key on the table so I made one (ROW_NUMBER()).You can tune the query by adjusting the @range variable.This will table scan. You can add some indexes to make it marginally faster (on the ID field) but it'll still be slow.Charlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION