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 tried AlexKuznetsov's solution but the result was 49 :(
My solution:
/* Create temporary table and set all dates into 1 column,
so we can sort by this one column */
DECLARE @tmp table (
Dates datetime,
IsStartedDate bit )
INSERT INTO @tmp
SELECT StartedOn, 1 FROM stats
UNION ALL
SELECT EndedOn, 0 FROM stats
DECLARE @currentlogins int, @highestlogins int, @IsStartedDate bit;
SET @currentlogins = 0;
SET @highestlogins = 0;
DECLARE tmp_cursor CURSOR FOR
SELECT IsStartedDate FROM @tmp
ORDER BY Dates ASC
OPEN tmp_cursor
/* Step through every row, if it's a starteddate increment @currentlogins else decrement it
When @currentlogins is higher than @highestlogins set @highestlogins to the new highest value */
FETCH NEXT FROM tmp_cursor
INTO @IsStartedDate
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@IsStartedDate = 1)
BEGIN
SET @currentlogins = @currentlogins + 1;
IF (@currentlogins > @highestlogins)
SET @highestlogins = @currentlogins;
END
ELSE
SET @currentlogins = @currentlogins - 1;
FETCH NEXT FROM tmp_cursor
INTO @IsStartedDate
END
CLOSE tmp_cursor
DEALLOCATE tmp_cursor
SELECT @highestlogins AS HighestLogins