Share a little trick to get the data with the smallest difference with yourself. The test data is as follows:
--Test Data if not object_id(N'Tempdb..#T1') is null drop table #T1 Go Create table #T1([code] int,[value] int) Insert #T1 select 1,10 union all select 2,50 union all select 3,100 GO if not object_id(N'Tempdb..#T2') is null drop table #T2 Go Create table #T2([code] int,[value] int) Insert #T2 select 1,15 union all select 2,35 union all select 3,45 Go -- end of test data
Use the ABS function to achieve:
SELECT *, ( SELECT TOP 1 [value] FROM #T2 ORDER BY ABS(#T1.value - #T2.value) ) FROM #T1;
The result is as follows: