SELECT * FROM (SELECT tm , ROW_NUMBER() OVER(ORDER BY x, tm) rn FROM (SELECT /*+ INDEX_DESC(t pk_t) */ tm , TO_TIMESTAMP(:v_tm, 'yyyy-mm-dd hh24:mi:ss.ff') - tm x FROM t WHERE id = :v_id AND tm <= TO_TIMESTAMP(:v_tm, 'yyyy-mm-dd hh24:mi:ss.ff') AND ROWNUM <= 3 UNION ALL SELECT /*+ INDEX(t pk_t) */ tm , tm - TO_TIMESTAMP(:v_tm, 'yyyy-mm-dd hh24:mi:ss.ff') x FROM t WHERE id = :v_id AND tm > TO_TIMESTAMP(:v_tm, 'yyyy-mm-dd hh24:mi:ss.ff') AND ROWNUM <= 3 ) ) WHERE rn <= 3 ;
SELECT * FROM (SELECT tm , ROW_NUMBER() OVER(ORDER BY x, tm) rn FROM (SELECT * FROM (SELECT tm , TO_TIMESTAMP(:v_tm, 'yyyy-mm-dd hh24:mi:ss.ff') - tm x , ROW_NUMBER() OVER(ORDER BY tm DESC) rn FROM t WHERE id = :v_id AND tm <= TO_TIMESTAMP(:v_tm, 'yyyy-mm-dd hh24:mi:ss.ff') ) a WHERE rn <= 3 UNION ALL SELECT * FROM (SELECT tm , tm - TO_TIMESTAMP(:v_tm, 'yyyy-mm-dd hh24:mi:ss.ff') x , ROW_NUMBER() OVER(ORDER BY tm) rn FROM t WHERE id = :v_id AND tm > TO_TIMESTAMP(:v_tm, 'yyyy-mm-dd hh24:mi:ss.ff') ) a WHERE rn <= 3 ) a ) a WHERE rn <= 3 ;