Results 1 to 4 of 4

Thread: nearest number

  1. #1
    Join Date
    Dec 2007
    Posts
    123
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default nearest number

    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)

  2. #2
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Code:
    SELECT * FROM my_table ORDER BY ABS(my_column - my_input) LIMIT 1;
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  3. The Following User Says Thank You to Twey For This Useful Post:

    cancer10 (03-09-2008)

  4. #3
    Join Date
    Dec 2007
    Posts
    123
    Thanks
    17
    Thanked 1 Time in 1 Post

    Default

    what does ABS do?

  5. #4
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Code:
    abs n | n < 0     = 0 - n
          | otherwise = n
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  6. The Following User Says Thank You to Twey For This Useful Post:

    cancer10 (03-09-2008)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •