tags:

views:

79

answers:

4

Hello Folks,

I have an adress table and I need to take the near number. For example if I´m entenring the number 256 in this case I´ll take 257 because: 254<--256->257

Somebody knows the solution.

Thanks and sorry for my bad English.

+3  A: 

The distance between 257 and the number is abs(number-257). So you can find (one of) the nearest numbers with:

select number
from (
    select number
    from yourtable
    order by abs(number-257)
) sub
where rownum < 2
Andomar
+2  A: 
SELECT  *
FROM    mytable
WHERE   mynumber BETWEEEN 256 - 2 AND 256 + 2

If you just need to pick the first match, use this:

SELECT  *
FROM    (
        SELECT  *
        FROM    (
                SELECT  *
                FROM    (
                        SELECT  *
                        FROM    mytable
                        WHERE   mynumber <= 256
                        ORDER BY
                                mynumber DESC
                        )
                WHERE   rownum = 1
                UNION ALL
                SELECT  *
                FROM    (
                        SELECT  *
                        FROM    mytable
                        WHERE   mynumber > 256
                        ORDER BY
                                mynumber
                        )
                WHERE   rownum = 1
                )
        ORDER BY
                ABS(256 - number), mynumber DESC
        )
WHERE   rownum = 1

This is more index efficient, since the final ORDER BY will sort at most two records.

Quassnoi
Thanks Quassnoi but your select don't take the following situation: 254<-255<-256->257->258I want to take one number, the nearest. We have other problem too because the two 255 and 257 are the nearest. We can make priority to the right number to solve this.
Daniel Maciel
Updated the query to select the larger record in case of a tie.
Quassnoi
Thanks Quassnoi, I'll try when my dblink comes back.
Daniel Maciel
+1 for a nice solution
David Aldridge
A: 

I tried the sql in other way but based on the Quassnoi´s SQL. I´ve made some revisions and it´s working well. Look:

(SELECT * FROM 
  (SELECT number 
    FROM numberList 
    WHERE number < ? 
    ORDER BY number DESC) 
    WHERE ROWNUM=1) 
    UNION ALL 
    (SELECT * FROM 
    (SELECT number  
    FROM numberList 
    WHERE numeber > ? 
    ORDER BY number ASC) 
    WHERE ROWNUM=1)
Daniel Maciel
A: 

Try this

Num integer := 236;

 select Max(number) AS NearestAndGreatest  from mytbl t
 join(
 select MIN(T.distance) AS dist from(
 select number,abs(number-Num) AS distance from mytbl)T)X
 on abs(number-Num) = X.dist
priyanka.sarkar