如果输入日期不可用,如何在 oracle 中获取开始日期和结束日期之间的输入日期然后 return 最大日期记录
How to get the input date between start and end date in oracle if input date not available then return max date record
请查找随附的示例数据。
场景 1:如果我提供的输入日期为“21-aug-20”,并且满足两个 aggrement_id,那么我希望获取 effective_end 上的最大记录。即 abcd。
场景 2:如果我提供日期“26-aug-20”并且在任何行中都不令人满意,那么它应该 return 最大有效结束日期记录。即 abce.
我使用了相同的数据并从中创建了一个 table demo
。见 dbfiddle
你能试试下面的查询吗,
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
我们可以使用 11g ROWNUM
。参见 dbfiddle
Note: I have not considered the scenario when the input provided is less than max(end_dt) and no match with any row.
请查找随附的示例数据。 场景 1:如果我提供的输入日期为“21-aug-20”,并且满足两个 aggrement_id,那么我希望获取 effective_end 上的最大记录。即 abcd。 场景 2:如果我提供日期“26-aug-20”并且在任何行中都不令人满意,那么它应该 return 最大有效结束日期记录。即 abce.
我使用了相同的数据并从中创建了一个 table demo
。见 dbfiddle
你能试试下面的查询吗,
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
我们可以使用 11g ROWNUM
。参见 dbfiddle
Note: I have not considered the scenario when the input provided is less than max(end_dt) and no match with any row.