简体   繁体   中英

How to get the input date between start and end date in oracle if input date not available then return max date record

Please find attached sample data. Scenario 1: If i provide input date as '21-aug-20' and it satisfies in two aggrement_id then i want the max record on effective_end to be taken. ie abcd . Scenario 2: If i Provide a date '26-aug-20' and which is not satisfying in any of the rows then it should return max effective end date record. ie abce .

PFA 样本数据

I have taken the same data and create a table demo out of it. see dbfiddle

Could you try with following query,

WITH data AS
 (SELECT DATE '2020-08-14' input FROM dual) --input parameter 
SELECT arng_id,st_dt,end_dt
FROM   (SELECT input
              ,demo.*
              ,MAX(end_dt) over(ORDER BY NULL) max_dt --taken max(end_dt) to match in case no result with input parameter
        FROM   demo
              ,data)
WHERE  (input BETWEEN st_dt AND end_dt)  -- matches with input paramater OR
OR     (max_dt BETWEEN end_dt AND input) -- condition when no result with first match 
ORDER  BY end_dt DESC -- order by require to fetch the max record always
FETCH  FIRST 1 ROW ONLY --oracle 12c feature

With 11g we can use ROWNUM . see dbfiddle

Note: I have not considered the scenario when the input provided is less than max(end_dt) and no match with any row.

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-2024 STACKOOM.COM