Puddle Puddle - 2 years ago 79
SQL Question

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


Answer Source

Order by run id descending and take only the first row:

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

See live demo on SQLFiddle.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download