2013-12-08 61 views
1

我有一個表有start_dateend_date時間戳,這些行包含來自半徑記帳​​表的數據。MySQL併發從行中選擇

用戶登錄後不久,用start_date時間戳插入一行,並且一旦用戶註銷,end_date將填充UPDATE。

這裏有幾排:

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號碼。

我可以通過逐行分析來做到這一點,但我想保留它作爲SQL查詢。

+0

看看成'GROUP BY'和'DAY(日期)'提取日期的一部分,用'COUNT(*)'可以顯示出現的次數。無法在不知道表結構的情況下給出完整查詢(對我來說)。 – skiwi

+0

看看這篇文章StackOverflow:http://stackoverflow.com/questions/1764881/mysql-getting-data-for-histogram-plot一些想法可能派上用場。 – GregD

回答

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 
0

你可以在每個數據點計算的併發用戶數,您有(起始/ 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