MySQL选择一段时间内

时间:2015-05-01 14:42:47

标签: mysql date concurrency overlap

我有一个表存储通过系统的所有呼叫。

我感兴趣的列只是calldate和callend,它们是通话的开始和结束时间。

我想在同一时间选择正在进行的并发呼叫数量。

我有一个查询可以返回所有重叠的调用,但这并不能完全满足我的要求。

SELECT SEC_TO_TIME(FLOOR((TIME_TO_SEC(t.calldate)+300)/600)*600) AS `TIME`,
     MAX(t.overlaps)
FROM(
    SELECT x.id,
           x.calldate,
           COUNT(y.id) overlaps
    FROM cdr x
    LEFT
    JOIN cdr y
      ON y.id <> x.id
     AND y.calldate < x.callend
     AND y.callend > x.calldate
     AND y.calldate BETWEEN '2015-05-01 00:00:00' AND '2015-05-01 23:59:59'
    WHERE
        x.calldate BETWEEN '2015-05-01 00:00:00' AND '2015-05-01 23:59:59'
    GROUP BY 
        x.id
) t
GROUP BY `TIME`;

这给了我一些正确的东西,但是因为它返回了所有重叠的调用,它实际上可能与之前完成的调用重叠,所以有些数字太高了。

Call    08:00    08:05    08:10    08:15    08:20    08:25
1         |-----------------|
2                  |-----------------|
3      |--------------|
4             |--------------------------------------|
5                               |--------------|
6                    |------------------------------------|    
       1  2   3    4 5 4     3  4     3         2     1   0

例如,因为它查看了呼叫ID而不是日期,所以会返回5,我只是不确定如何更改它让它正确使用日期。

我可能错过了一些简单的事情,但这是漫长的一天。

修改

使用edTarik的答案,这有效:

SELECT y.`Interval`,
         @lines := CAST((@lines + y.t) AS INT) as TotayQuantity
FROM 
    (SELECT @lines := 0) init,
    (
        SELECT 
            SEC_TO_TIME(FLOOR((TIME_TO_SEC(x.cd)+300)/600)*600) as `Interval`, 
            SUM(x.t) as t 
        FROM 
            (   
                SELECT 
                    calldate as cd, 
                    1 as t 
                FROM cdr c
                WHERE 
                    calldate BETWEEN '2015-05-04 00:00:00' AND '2015-05-04 23:59:59'
                UNION ALL
                SELECT 
                    callend as cd, 
                    -1 as t 
                FROM cdr c
                WHERE 
                    callend BETWEEN '2015-05-04 00:00:00' AND '2015-05-04 23:59:59'
                ORDER BY cd
            ) x 
        GROUP BY `Interval`
    ) y

1 个答案:

答案 0 :(得分:0)

您需要执行以下操作:

Select calldate, 1 From cdr
Union
Select callend, -1 from cdr
Order by calldate

然后选择累计总和,然后找到最大值。见How to get running sum of a column in sql server