1

I have a table.

this table has usage period of user.

example is follow

|user_id|start_at  |end_at    |
|1      |2014/11/02|2014/11/05|
|2      |2014/11/03|2014/11/07|
|3      |2014/11/08|2014/11/09|

I would like to get maximum concurrent number of users

above case,

Between 2014/11/03 ~ 2014/05, 2 user used.

I would like to get this "2".

Is there an easy way to set this up? What do you recommend?

tamagohan2
  • 445
  • 4
  • 15
  • Where are "Users" ? What You specified is UserId.. – SonalPM Nov 14 '14 at 12:58
  • possible duplicate of [SQL COUNT between dates in two different column](http://stackoverflow.com/questions/16384273/sql-count-between-dates-in-two-different-column) – Tab Alleman Nov 14 '14 at 13:48

3 Answers3

3

The maximum is going to occur at one of the start_at times. So, you can do this with a self-join:

select u.start_at, count(*) as numconcurrent
from usage u join
     usage u2
     on u.start_at between u2.start_at and u2.end_at
group by u.start_at

If you want the maximum number, then add:

order by count(*) desc
limit 1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

sounds like you may have mis-stated the question. Do you really mean "max" ? or just the number of users between two dates ? If that is so, then

Select count(*) from table 
where start_at < @end
   and end_at > @start
Charles Bretana
  • 143,358
  • 22
  • 150
  • 216
0
sum(case when start_at >= @startdate and end_at <= @enddate 
          then 1 
          else 0 
    end) as total

this would follow a qualifying set declare statement or embedded in a stored procedure. Your choice.

This will increment by 1 every time it sees a row that meets those credentials and sum the total.

Saravana Kumar
  • 3,669
  • 5
  • 15
  • 35
SFrejofsky
  • 732
  • 5
  • 16