分享一个小技巧,获取和自己差值最小的数据,测试数据如下:
--测试数据
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
--测试数据结束
利用ABS函数来实现:
SELECT *,
(
SELECT TOP 1 [value] FROM #T2 ORDER BY ABS(#T1.value - #T2.value)
)
FROM #T1;
结果如下: