Skip to content
Advertisement

SQL – Get the MAX COUNT access peak having only entrance and exit date

I have a table that keeps the access to our system, and it have two columns called entranceTime and exitTime

Eg:

What im trying to get is the “peak” of simultaneous connections, i tried using a subquery with MAX and COUNT like this:

But with this query im getting the count of 5 instad of 3, is it possible to achieve this with only this two columns and using only SQL? Thank you for your time.

Advertisement

Answer

The “peak” is going to occur at one of the entrance times. You can use a correlated subquery to count the number of concurrent rows at each one. And then get the peak:

The above may not scale well, so there is actually a more efficient way. You can unpivot the times and use cumulative sums:

Here is a db<>fiddle.

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