Skip to content
Advertisement

How to count the Gap between dates in SQL Server with overlapping dates

I’m trying to get the GAP (In days) between records in one Table, I’m using SQL Server.

So far, I was able to get the gap (in days) between dates, but there was an issue with the overlapping dates.

Here is the setup script:

Here is my query:

Result:

Expected Results:

The goal was to get the gap with respect to the overlapping dates

Advertisement

Answer

I don’t quite follow your results.

I think the problem is a combination of gaps-and-islands along with “fill-in-gaps”. That is, you need to combine the existing data that overlaps. Then you need to get the pieces in-between.

You can identify the overlaps by using a cumulative max of the end date from preceding rows. When it is less than or equal to the current start, then you have a new “island”. The result is aggregation and lead().

The code looks like this:

Here is the db<>fiddle.

The results are subtly different, but they make more sense to me.

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