2015-04-21 27 views
2

之間的區別這是我的查詢: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 calldate asc 

返回如下:

Mysql query

我如何添加第4列擺脫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_end來自呼叫,應該有一個空。

SOLUTION:

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; 

輸出:

Output

+0

轉換兩個日期以unix時間戳格式,然後你可以找到差異。 –

+0

@noddy問題不是轉換,問題是我無法找到查詢的邏輯 – Alpha2k

+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 ext = '2602' -- ext is the primary key 
AND DATE_FORMAT(calldate, '%Y-%m-%d') = "2015-03-20" 
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 
相關問題