Skip to content
Advertisement

Group Records based on predefined date range in SQL (Oracle)

Is it possible to group records based on a predefined date range differences (e.g. 30 days) based on the start_date of a row and the end_date of the previous row for non-consecutive dates? I want to take the min(start_date) and max(end_date) of each group. I tried the lead and lag function with partition by in Oracle but couldn’t come up with a proper solution. A related but unanswered post related to my question can be found here.

E.g.

Expected Result:

Advertisement

Answer

Use lag() and a cumulative sum to define where the groups begin. Then aggregate:

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