Вам не нужно делать это рекурсивно, вы можете использовать not exists
для проверки любых случаев в течение трех месяцев:
-- CTE for sample data
with your_table (policy_no, casenumber, created_date) as (
select 17850850, 4150778, date '2019-04-16' from dual
union all select 17850850, 3955549, date '2019-01-22' from dual
union all select 17850850, 3188447, date '2018-05-14' from dual
union all select 17850850, 2998931, date '2018-03-14' from dual
union all select 17850850, 2767545, date '2017-12-29' from dual
union all select 17850850, 2420594, date '2017-09-17' from dual
)
-- actual query
select policy_no, casenumber, created_date
from your_table t
where policy_no = 17850850
and not exists (
select *
from your_table t2
where t2.policy_no = t.policy_no
and t2.casenumber != t.casenumber
and t2.created_date >= t.created_date
and t2.created_date <= add_months(t.created_date, 3)
)
order by policy_no, created_date desc;
POLICY_NO CASENUMBER CREATED_DATE
---------- ---------- ------------
17850850 4150778 2019-04-16
17850850 3188447 2018-05-14
17850850 2420594 2017-09-17
Если вы хотите просмотреть все строки с разницей по месяцами последний / исключенный / включенный флаг, как показано в отредактированном вопросе, вместо этого вы можете использовать встроенное представление, чтобы найти следующую созданную дату и разницу, а затем установить флаг на основе этого во внешнем запросе:
-- with same CTE for sample data
select policy_no, casenumber, created_date,
trunc(diff, 2) as diff,
case when diff is null then 'latest'
when diff <= 3 then 'excluded'
else 'included'
end as outcome
from (
select policy_no, casenumber, created_date,
months_between(lead(created_date) over (partition by policy_no order by created_date),
created_date) as diff
from your_table t
)
where policy_no = 17850850
order by policy_no, created_date desc;
POLICY_NO CASENUMBER CREATED_DATE DIFF OUTCOME
---------- ---------- ------------ ---------- --------
17850850 4150778 2019-04-16 latest
17850850 3955549 2019-01-22 2.8 excluded
17850850 3188447 2018-05-14 8.25 included
17850850 2998931 2018-03-14 2 excluded
17850850 2767545 2017-12-29 2.51 excluded
17850850 2420594 2017-09-17 3.38 included
Вы можете использовать тот же подход для просмотра строк, чтобы получить только включенные строки:
-- with same CTE
select policy_no, casenumber, created_date
from (
select policy_no, casenumber, created_date,
months_between(lead(created_date) over (partition by policy_no order by created_date),
created_date) as diff
from your_table t
)
where policy_no = 17850850
and (diff is null or diff > 3)
order by policy_no, created_date desc;
POLICY_NO CASENUMBER CREATED_DATE
---------- ---------- ------------
17850850 4150778 2019-04-16
17850850 3188447 2018-05-14
17850850 2420594 2017-09-17
db <> fiddle