Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Clearly the number of concurrent users only changes when a user either starts or ends a period, so it is enough to determine the number of concurrent users during starts and ends. So, reusing test data provided by Remus (thank you Remus):</p> <pre><code>DECLARE @Table TABLE ( UserId int, StartedOn datetime, EndedOn datetime ); insert into @table (UserId, startedOn, EndedOn) select 1, '2009-7-12 14:01', '2009-7-12 15:01' union all select 2, '2009-7-12 14:30', '2009-7-12 14:45' union all select 3, '2009-7-12 14:47', '2009-7-12 15:30' union all select 4, '2009-7-12 13:01', '2009-7-12 17:01' union all select 5, '2009-7-12 14:15', '2009-7-12 18:01' union all select 6, '2009-7-12 11:01', '2009-7-12 19:01' union all select 1, '2009-7-12 16:07', '2009-7-12 19:01'; SELECT MAX(ConcurrentUsers) FROM( SELECT COUNT(*) AS ConcurrentUsers FROM @table AS Sessions JOIN (SELECT DISTINCT StartedOn AS ChangeTime FROM @table ) AS ChangeTimes ON ChangeTime &gt;= StartedOn AND ChangeTime &lt; EndedOn GROUP BY ChangeTime ) AS ConcurrencyAtChangeTimes ------- 5 </code></pre> <p>BTW using DISTINCT per se is not a mistake - only abusing DISTINCT is. DISTINCT is just a tool, using it in this context is perfectly correct.</p> <p><strong>Edit:</strong> I was answering the OP's question: "how one could calculate this using T-SQL only". Note that the question does not mention performance.</p> <p>If the questions was this: "what is the fastest way to determine maximum concurrency if the data is stored in SQL Server", I would provide a different answer, something like this:</p> <p>Consider the following alternatives</p> <ol> <li>Write a cursor </li> <li>Write a CLR cursor</li> <li>Write a loop on the client</li> <li>Use an RDBMS with decent cursors, such as Oracle or PostgreSql</li> <li>For top performance, design your table differently, so that you can retrieve the answer in one index seek. This is what I do in my system if I need to deliver best possible performance.</li> </ol> <p>If the question was "what is the fastest way to determine maximum concurrency using a T-SQL query", I would probably not answer at all. The reason: if I needed really good performance, I would not solve this problem in a T-SQL query.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload