nearest number

Reply

Join Date: Dec 2004
Posts: 234
Reputation: cancer10 is an unknown quantity at this point 
Solved Threads: 0
cancer10's Avatar
cancer10 cancer10 is offline Offline
Posting Whiz in Training

nearest number

 
0
  #1
Mar 8th, 2008
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)
Reply With Quote Quick reply to this message  
Join Date: Mar 2008
Posts: 100
Reputation: petr.pavel is an unknown quantity at this point 
Solved Threads: 14
petr.pavel's Avatar
petr.pavel petr.pavel is offline Offline
Junior Poster

Re: nearest number

 
0
  #2
Mar 8th, 2008
Hi there,
try something along these lines:
  1. SELECT columnName, ABS(columnName - 9) AS distance
  2. ORDER BY distance LIMIT 1

Could be that ORDER BY won't accept alias distance in which case you'll have to repeat the ABS() code. The trick is in calculating the distance of your number (9) and your column values.

In PHP you then use something like:
$result = mysql_query("SELECT ... ABS(columnName - $myNumber) ...");
list($closestNumber) = mysql_fetch_row($result);

Let me know if this helps.
Petr 'PePa' Pavel
Reply With Quote Quick reply to this message  
Join Date: Dec 2004
Posts: 234
Reputation: cancer10 is an unknown quantity at this point 
Solved Threads: 0
cancer10's Avatar
cancer10 cancer10 is offline Offline
Posting Whiz in Training

Re: nearest number

 
0
  #3
Mar 8th, 2008
what does ABS do?
Reply With Quote Quick reply to this message  
Join Date: Mar 2008
Posts: 100
Reputation: petr.pavel is an unknown quantity at this point 
Solved Threads: 14
petr.pavel's Avatar
petr.pavel petr.pavel is offline Offline
Junior Poster

Re: nearest number

 
0
  #4
Mar 9th, 2008
Originally Posted by cancer10 View Post
what does ABS do?
Calculates absolute value: ABS(-10) = 10, ABS(10) = 10
Last edited by petr.pavel; Mar 9th, 2008 at 7:39 am.
Petr 'PePa' Pavel

The more information you give the more relevant answer you get.
Please consider using "Add to ... Reputation" and mark your thread as Solved if you found what you were looking for. By giving feedback you help others.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC