这是我的疑问:
select calldate as call_start, DATE_ADD(calldate, Interval duration SECOND) as call_end, duration
from extensions
where ext = '2602' -- ext is the primary key
AND DATE_FORMAT(calldate, '%Y-%m-%d') = "2015-03-20"
order by calldate asc
返回以下内容:
如何添加第4列以区分第二行的call_start - 第一行的call_end?像这样:
2015-03-20 10:21:20 - 2015-03-20 10:21:16 => 4秒,这4秒应该作为第二行的第4个字段添加。
所以看起来应该是所有的电话:
call_start call_end duration difference
2015-03-20 10:19:41 2015-03-20 10:21:16 95 null
2015-03-20 10:21:20 2015-03-20 10:21:29 9 4
由于第一行之前的调用没有call_end,因此应该为null。
解决方案:
SET @prev_end=null;
select calldate, date_add(calldate, interval duration SECOND) as end_date, duration,
TIME_FORMAT(SEC_TO_TIME(timestampdiff(second,@prev_end,calldate)), '%i:%s')as difference,
@prev_end:= date_add(calldate, interval duration SECOND) as test
from extensions
where ext = '2602'
AND DATE_FORMAT(calldate, '%Y-%m-%d') = "2015-03-20"
order by calldate asc;
输出:
答案 0 :(得分:3)
考虑下表
mysql> select * from extensions;
+---------------------+----------+
| calldate | duration |
+---------------------+----------+
| 2015-03-20 10:19:41 | 95 |
| 2015-03-20 10:21:20 | 9 |
| 2015-03-20 10:21:35 | 277 |
| 2015-03-20 10:55:49 | 27 |
+---------------------+----------+
现在你可以得到差异
select
calldate as start_date,
end_date,
duration,
difference
from(
select
calldate,
duration,
date_add(calldate, interval duration SECOND) as end_date ,
timestampdiff(second,@prev_end,calldate) as difference,
@prev_end:= date_add(calldate, interval duration SECOND)
from extensions,(select @prev_end:=null)x
order by calldate
)x
+---------------------+---------------------+----------+------------+
| start_date | end_date | duration | difference |
+---------------------+---------------------+----------+------------+
| 2015-03-20 10:19:41 | 2015-03-20 10:21:16 | 95 | NULL |
| 2015-03-20 10:21:20 | 2015-03-20 10:21:29 | 9 | 4 |
| 2015-03-20 10:21:35 | 2015-03-20 10:26:12 | 277 | 6 |
| 2015-03-20 10:55:49 | 2015-03-20 10:56:16 | 27 | 1777 |
+---------------------+---------------------+----------+------------+
在上面的查询中,您需要在where子句之前在子查询中添加额外的where子句
where ext = '2602' -- ext is the primary key
AND DATE_FORMAT(calldate, '%Y-%m-%d') = "2015-03-20"
答案 1 :(得分:0)
您可以使用MySQL用户定义的变量。 以下是可以帮助您的查询:
SET @end=null; -- reset the variable
SELECT
calldate as call_start,
DATE_ADD(calldate, Interval duration SECOND) as call_end,
TIMESTAMPDIFF(SECOND, call_start, @end) as prev_diff,
@end:=DATE_ADD(calldate, Interval duration SECOND)
FROM extensions
WHERE ext = '2602' -- ext is the primary key
AND DATE_FORMAT(calldate, '%Y-%m-%d') = "2015-03-20"
ORDER BY calldate asc