Skip to content
Advertisement

Detect overlapping date ranges from the same table

I have a table with the following data

And want to get the following results

Any ideas on where to start? A lot of the reading I’ve done suggests I need to create entries and for each day and join on matching days, is this the only way?

Advertisement

Answer

If you already have entries for each day that should work, but if you don’t the overhead is significant, and if that query is used often, if will affect performance.

If the data is in this format, you can detect overlaps using simple date arithmetic, because an overlap is simply one interval starting after a given interval, but before the given is finished, something like

If you need special handling for interval that are wholly within another interval, or you need to merge intervals, i.e.

yielding

you will need more complex calculation.

In my experience with this kind of problems, once you get how to do the calculation by hand, it’s easy to transfer it into SQL 🙂

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