简体   繁体   English

如果输入日期不可用,如何在 oracle 中获取开始日期和结束日期之间的输入日期,然后返回最大日期记录

[英]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.场景 1:如果我提供输入日期为 '21-aug-20' 并且它满足两个 aggrement_id,那么我希望获取有效结束的最大记录。 ie abcd .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.场景 2:如果我提供了一个日期 '26-aug-20' 并且在任何行中都不令人满意,那么它应该返回最大有效结束日期记录。 ie abce .abce

PFA 样本数据

I have taken the same data and create a table demo out of it.我已经获取了相同的数据并从中创建了一个表格demo see dbfiddledbfiddle

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 .对于 11g,我们可以使用ROWNUM see dbfiddledbfiddle

Note: I have not considered the scenario when the input provided is less than max(end_dt) and no match with any row.注意:我没有考虑提供的输入小于 max(end_dt) 并且与任何行都不匹配的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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