Skip to content
Advertisement

Recursive Query Sql Oracle 3 months difference between dates

I have a simply table with three columns, policy_no, casenumber and created_date. Multiple casenumbers can be logged against unique policy numbers. I need a query that runs through the data finds the earliest case for a policy, and then checks the difference between that and the next one. If the difference is greater than three months it includes the first case, if the difference is shorter, it exclude the first case and then moves on to the second case and again checks the difference between that and the third case. Basically, I only want to include cases which did not have another case raised raised within the next three months.

Would return the following results;

The first case raised on 05/09/2017 should be included, as no further case was raised until 29/12/2017 (so greater than 3 months). The case raised on 29/12/2017 should be excluded as a case was raised on 14/03/2018. The case raised on 14/03/2018 should also be excluded, as another case was raised on 14/05/2018 (within 3 months). The case raised on 14/05/2018 should be included, 22/01/2019 should be excluded, and 16/04/2019 should be temporarily included (subject to no further case being raised within the following three months). Any help would be much appreciated. Looking to get to this;

Advertisement

Answer

You don’t need to do this recursively, you can use not exists to check for any cases within three months:

If you want to see all rows with the month-based difference and the latest/excluded/included flag, as shown in your edited question, then you can instead use an inline view to find the next created date and the difference, and then work out the flag based on that in an outer query:

You could use the same inline-view approach to get just the included rows instead:

db<>fiddle

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement