Search code examples
sqloracle11ggroupwise-maximum

Selecting entries with nearest value less than given value


I want to select the entries with the nearest value less than a given value with SQL (No PL/SQL! or such thing).

I got this far:

select max(RUN_ID) from RUN_TABLE where KEY = 'TEST#33' and RUN_ID < 3

This returns the row with the highest value less than 3 matching the key but I want to be able to select all columns.

Run_ID  Entity  Key
1         HK    TEST#11
2         AB    TEST#22
2         CK    TEST#33
3         TB    TEST#22
3         DB    TEST#33

I would like to be able when having the key TEST#22 and maximal RUN_ID 4 to select the row:

3   TB   TEST#22 

And when saying maximal RUN_ID 2 to retrieve

2   AB   TEST#22

Solution

  • Order by run id descending and take only the first row, for Oracle:

    select top 1 * from RUN_TABLE
    where KEY = 'TEST#33' and RUN_ID < 3
    order by RUN_ID desc
    fetch first 1 rows
    

    Or SQL Server (because SQLFiddle's Oracle option is down):

    select top 1 * from RUN_TABLE
    where KEY = 'TEST#33' and RUN_ID < 3
    order by RUN_ID desc
    

    with live demo on SQLFiddle.