我有一个具有start_date
和end_date
时间戳的表,这些行包含来自radius accounting表的数据。
用户登录后不久,会插入一行start_date
时间戳,一旦用户注销,end_date
就会填充更新。
以下是几行:
ID | start_date | end_date
22 2013-11-19 12:00:22 2013-11-20 14:20:22 (*)
23 2013-11-19 12:02:22 2013-11-20 15:20:22 (*)
23 2013-11-19 17:02:22 2013-11-20 20:20:22
24 2013-11-20 12:06:22 2013-11-20 15:20:22 *
25 2013-11-20 12:40:22 2013-11-20 15:23:22 *
26 2013-11-20 12:50:22 2013-11-20 17:23:22 *
27 2013-11-20 16:56:22 2013-11-20 17:29:22
28 2013-11-20 17:58:22 2013-11-20 20:24:22
所以在这种情况下,对于2013-11-19,并发用户的最大数量是2(标有(*))(它们在开始和结束重叠之间的时间),对于2013-11-20它是3(标记为与*)
我正在尝试编写一个SQL查询来获取一天中大多数并发用户的数量(基于开始日期和结束日期),因此一个简短的结果将是在2013-08-12,在线最多同时是xx数。
我可以通过逐行分析在PHP中执行此操作,但我希望将其保留为SQL查询。
答案 0 :(得分:2)
尝试
select d, count(*) as user_count
from
(
select start_date as d from your_table
union all
select end_date as d from your_table
) x
group by d
order by user_count desc
答案 1 :(得分:0)
您可以计算每个数据点上的并发用户数(start_date / end_date),然后计算出最大值:
select max(cnt)
from (
select q.t, count(*) as 'cnt'
from (
select start_date as 't'
from log
where start_date between YOUR_START_DATE and YOUR_END_DATE
union
select end_date
from log
where end_date between YOUR_START_DATE and YOUR_END_DATE
) as q
join log l on q.t between l.start_date and l.end_date
group by q.t
) a