I have the table of following structure:
UserID StartedOn EndedOn
1 2009-7-12T14:01 2009-7-12T15:01
2 2009-7-12T14:30 2009-7-12T1
I did the work using integers rather than datetime fields, but I believe the following sql snippet gets you what you want.
Basically, I compared the start and end date of each user against each other using a self-join. If User A started before or at the same time as User B AND User B started before or at the same time as User A ended, they are running concurrently. Thus, I found the user with the max number of concurrent users (and added 1 for themselves since I excluded them in the self-join.)
I noticed you have multiple rows for each user. Please note the sql below assumes the same user can't be running multiple instances at once (concurrently.) If this assumption doesn't hold true, I'm hoping you have an additional column which is unique per row. Use this column rather than UserId throughout the sql routine.
I've gotten you really close. I hope this helps. Best of luck.
DECLARE @Table TABLE
(
UserId int,
StartedOn int,
EndedOn int
)
Insert Into @Table
Select 1, 1, 3
union
Select 2, 2, 4
union
Select 3, 3, 5
union
Select 4, 4, 6
union
Select 5, 7, 8
union
Select 6, 9, 10
union
Select 7, 9, 11
union
Select 8, 9, 12
union
Select 9, 10, 12
union
Select 10, 10, 13
--Select * from @Table
Select
A.UserId,
Count(B.UserId) + 1 as 'Concurrent Users'
FROM @Table A, @Table B
WHERE A.StartedOn <= B.StartedOn
AND B.StartedOn <= A.EndedOn
AND A.UserId != B.UserId
Group By A.UserId
Order By Count(B.UserId) Desc