简体   繁体   中英

Get most approximated value in SQL

I have a table with rows fruit and price for example:

Apple - 1

Melon - 3

Orange - 10

Pear - 5

And I want to make a query to get the fruit with price more approximated to the value I will pass.

Something like:

SELECT * 
FROM fruit
WHERE condition

Any help will be appreciated.

Is this what you want?

SELECT f.* 
FROM fruit f
ORDER BY ABS(f.price - 7)
LIMIT 1;

This gets the fruit whose price is closest to 7. Of course, "7" is a parameter that could be any value.

Well, the comments pretty much have the answer:

SELECT * FROM fruit  
WHERE abs(price-@searchprice) =
  (SELECT abs(price-@searchprice) 
  FROM fruit ORDER BY abs(price-@searchprice) LIMIT 1)

The subquery finds the price difference from the entered price (@searchprice - change the parameter name style according to the needs of your database/driver combination) to the nearest 1 actual price

This is then used to look up all fruit that has a difference equal to that price difference. We do this so that any items tied on price are returned - in your example data if searchprice was 2 then Apple and Melon are both equally near and should be returned

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM