以下是一些示例数字:
987
1001
1004
1009
1010
1016
1020
1050
例如,我想选择接近给定数字1009
的前4位数字(因此,结果将是1001
,1004
,1010
和1016
),我该如何编写SQL表达式?
答案 0 :(得分:7)
通过减去并使用abs
函数来获取给定数字的距离:
select top 4 Number
from NumberTable
where number <> 1009
order by abs(Number - 1009)
正如您现在提到的,您有一个非常大的表,您需要一种方法来首先消除大部分结果。你可以在两个方向上选择最接近的四个,然后从中得到正确的:
select top 4 Number
from (
select Number
from (
select top 4 Number
from NumberTable
where number < 1009
order by number desc
)
union all
select Number
from (
select top 4 Number
from NumberTable
where number > 1009
order by number
)
)
order by abs(Number - 1009)
如果数字均匀分布,以确保您可以找到范围内的数字,例如+ -100个数字,那么您可以先得到该范围:
select top 4 Number
from (
select Number
from NumberTable
where number between 1009-100 and 1009+100
)
where number <> 1009
order by abs(Number - 1009)
答案 1 :(得分:2)
SELECT TOP 4 number
FROM your_table
WHERE number <> @numberToMatch
ORDER BY ABS(number - @numberToMatch)
答案 2 :(得分:2)
从本页的所有其他答案中取出一些内容!
假设number
列上的索引应该运行良好(至少在SQL Server中)
DECLARE @Target int
SET @Target = 1009;
SELECT TOP 4 number
FROM
(
SELECT TOP 4 number from YourTable
WHERE number < @Target
ORDER BY number desc
UNION ALL
SELECT TOP 4 number from YourTable
WHERE number > @Target
ORDER BY number asc
) d
order by abs(number - @Target)
答案 3 :(得分:1)
试试这个:
DECLARE @Target int
SET @Target = 1009
SELECT TOP 2 number from TABLE
WHERE number < @Target
ORDER BY number desc
UNION
SELECT TOP 2 number from TABLE
WHERE number > @Target
ORDER BY number asc