Skip to content
Advertisement

How to get maximum number of concurrent events in postgresql?

I have a table named events like this:

These events could have overlaps, and I want to know maximum number of overlapping events that have occurred over a time span. For example, in a situation like this:

The answer is 2, because at most 2 events overlap at 10:30 until 10:35.
I’m using Postgres 9.6

Advertisement

Answer

Here is the idea: count the number of starts and subtract the number of stops. That gives the net amount at each time. The rest is just aggregation:

The subquery shows the number of overlapping events at each time.

You can get the time frame as:

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