MySQL查找两个日期不同列之间的差异
这是我的疑问:MySQL查找两个日期不同列之间的差异,mysql,Mysql,这是我的疑问: 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
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
返回以下内容:
如何添加第四列以获得第二行的call_start与第一行的call_end之间的差异?大概是这样的:
2015-03-20 10:21:20-2015-03-20 10:21:16=>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\u 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;
输出:
考虑下表
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"
您可以使用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
将两个日期都转换为unix时间戳格式,然后您就可以找到差异。@Nodedy问题不是转换,问题是我找不到查询的逻辑。您能告诉我差异列的含义吗?@Nodedy获取call_从第二行开始与call_从第一行结束之间的差异,依此类推。。