简体   繁体   中英

Select tow row where before and after specific create date

I have an table with create date column. Is there anyway to select exact tow rows that have create date before and after specified date in one select statement without inner query and join?

Id - date
1 - 1/1/2013
2 - 2/1/2013
3 - 6/1/2013
4 - 9/2/2014

For 4/1/2013 result is:

2 - 2/1/2013
3 - 6/1/2013

You can use row_number() :

select t.*
from (select t.*,
             row_number() over (partition by sign(date - date '2013-04-01')
                                order by abs(date - date '2013-04-01') as seqnum
                               ) as seqnum
      from t
     ) t
where seqnum = 1;

This could return three rows -- if a date exactly matches. I view this as a feature, because you don't specify what to do in that case.

In Oracle 12C, you can do:

select t.*
from t
order by row_number() over (partition by sign(date - date '2013-04-01')
                            order by abs(date - date '2013-04-01')
                           )
fetch first 2 rows only;

Note: If one of the dates matches the incoming date, the results are indeterminate (among the three possible dates).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM