Cell Phones - Free Ringtones - Mobile Phones - Remortgages - Loan

PDA

View Full Version : nearest number


cancer10
Mar 8th 2008, 6:46 am
If you have a column, of data type = INT, with the following numbers
as separate rows.
1
3
4
5
7
10


How can you write a sql statement where you can calculate the
nearest number to any give input.
Example , if the input is 9 ? (the answer is 10)
If the input is 8 (the anwer is 7)

AstarothSolutions
Mar 8th 2008, 10:01 am
You dont say which SQL you are using.... with SQL Server it would be something like:

SELECT TOP (1) NumberCol
FROM NearestNumber
ORDER BY ABS(NumberCol - @Query);

cancer10
Mar 8th 2008, 10:13 am
I use mysql

AstarothSolutions
Mar 9th 2008, 12:41 am
Well Top (1) becomes Limit (0,1) from memory, ABS() is the same in both and as your also probably a php person you will replace the @Query parameter with inline insertion of the number

kmap
Mar 14th 2008, 7:43 am
"SELECT `NumberCol` FROM `NearestNumber` ORDER BY ABS(NumberCol -$n) limit(0,1)";

i think this is what he means and full marks

Regards

alex