Oracle FAQ | Your Portal to the Oracle Knowledge Grid |
Home -> Community -> Usenet -> c.d.o.server -> SQL question - find rows surrounding criteria
This may be an old question, but I'm not sure where to search
the web to find my answer.
I have a table with stock quotes. It looks like:
id tms Price -----------------------------
I'd like to retrieve the 2 stock quotes that are closest to the date I supply. I want one row that is the closest <= to the date I supply, and the other that is closest >= the date I supply.
For example if supply "1/2/04 12:00:00" to the query, it would return rows:
3 1/2/04 08:00:00 50.85
4 1/2/04 17:00:00 49.40
But if I supplied "1/2/04 18:00:00" it would return:
4 1/2/04 17:00:00 49.40
5 1/3/04 08:00:00 48.90
The only way I can think to do it is like below, but its expensive when my table is very long
select *
from quote
where tms in (
select max(tms)
from quote where tms <= to_date('&date','MM/DD/YYYY hh24:MI:SS')union
from quote where tms >= to_date('&date','MM/DD/YYYY hh24:MI:SS'))
Thanks
Jay
Received on Wed Jul 21 2004 - 08:54:03 CDT