1

I have a table like below:

enter image description here

The record of id = 1, means that value >0 and value <=200.

The record of id = 2, means that value >200 and value <=1500.

The values are ordered by such analogy.

Now I have a value of 4000, I want to get the corresponding id value(should be 4).

Are there better way to write SQL compare with?

select * from table_name where value >=4000 and rownum = 1;

1
  • 1
    the code you have now returns 4 right?
    – Jeremy C.
    May 20, 2015 at 8:57

2 Answers 2

2

Here is a simnple test case with analytic functions

create table test (id number, value number);
insert into test values(1,200);
insert into test values(2,1500);
insert into test values(3,3200);
insert into test values(4,4500);
commit;
select * from (
 SELECT id, value as min, 
     LAG(value, 1, 0 ) OVER (ORDER BY id desc) as max from test
     order by id) 
where 4000>=min AND 4000<max

The inner query uses LAG to provide a view that exposes the data as a range you can easily query

0
SELECT MAX(id)
FROM table
WHERE value <= 4000

If you want all the data (id and value)

SELECT *
FROM table
WHERE id = (SELECT MAX(id)
            FROM table
            WHERE value <= 4000)

NOTE: this will only work if your values are in order (meaning the value for id 1 is smaller than the value for id 2, value for id 2 is smaller than value for id 3 etc...)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.