开发者

How to select similar numbers using SQL?

Here are some example numbers:

987
1001
1004
1009
1010
1016
1020
1050

For example, I would like select the top 4 numbers that close to the given number 1009 (so, the results would be 1001开发者_开发百科, 1004, 1010 and 1016), how should I write the SQL expression?


Get the distance from the given number by subtracting and using the abs function:

select top 4 Number
from NumberTable
where number <> 1009
order by abs(Number - 1009)

Edit:

As you now mention that you have a very large table, you would need a way to elliminate most of the results first. You could pick the four closest in both direction and then get the correct ones from that:

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)

If the numbers are evenly distributed so that you are sure that you can find the numbers in a range like for example +-100 numbers, you can simply get that range first:

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)


SELECT TOP 4 number
FROM your_table
WHERE number <> @numberToMatch
ORDER BY ABS(number - @numberToMatch)


Taking bits from all other answers on this page!

Assuming an index on the number column this should perform well (at least in 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)


Try this:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜