Skip to content
Advertisement

SQL consolidate overlapping dates based on criteria

I’m trying to merge overlapping dates between Admit and discharge dates of patients. There are a few edge cases which I couldn’t cover in the query.

Input

Expected Output

Query I used the logic that was here But this doesn’t cover the edge case for ID 2 and 3. Also the subquery is slower when the data is huge. Is it possible to tackle this problem using LAG?

Advertisement

Answer

This is a type of gaps-and-islands problem. I would suggest using a cumulative max to determine when an “island” starts and then aggregate:

Here is a db<>fiddle.

The innermost subquery is retrieving the maximum discharge date before each row. This allows you to check for an overlap. The middle subquery counts up the number of times there is no overlap — the beginning of a group. And the outer query aggregates.

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