Skip to content
Advertisement

Unioning overlapping time ranges, then summing the total time

I have a hardware group and many devices into this group. Example:

All devices are monitored using ping. When some device is not working the program add a row into a table saying the start of break. When the device back on then the program update this row saying the end of break.

It’s ok to know the total break seconds for each device. My need is know the real sum time of all group. Example:

The real down time of group “Room 1” is 39 seconds (NOT 58).

About the two first lines, take a look why is 27 seconds and not 46 seconds:

Well… I have many groups and many devices per group. How can I do it using SQL?

To help on tests…

Advertisement

Answer

You are looking to combine the different groups into “islands” and to count the extend of the islands. That is why this type of problem is sometimes called gaps and islands.

Let me assume that you are using SQL Server 2012+. That slightly simplifies the calculations. The idea is to determine the starts and ends for overlapping groups. The following determines if a group has overlaps:

With this, you can just assign to each row in the table the number of “NoOverlapBefore” records that occur before it and use result for aggregation:

EDIT:

I misunderstood a few things about your data structure. The SQL Fiddle is a big help. Here is one that actually works.

The query is:

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