开发者

SQL time difference within single table

I have a single MySQL table with login data of users.

user |  date               | type
-----+---------------------+------
1    | 2011-01-05 08:00:00 | login
1    | 2011-01-06 09:00:00 | login
1    | 2011-01-06 10:00:00 | logout
1    | 2011-01-06 09:50:00 | login

Given the开发者_JS百科 above table I would like to calculate the time difference between the logout date and the previous login date by adding a new cell called duration. E.g. the logout date was '2011-01-06 10:00:00; and the previous login date would be '2011-01-06 09:50:00'.

The result should look somehow like this. Rows with type=login should not have a duration value.

user |  date               | type   | duration
-----+---------------------+--------+----------
1    | 2011-01-05 08:00:00 | login  | -
1    | 2011-01-06 09:00:00 | login  | -
1    | 2011-01-06 10:00:00 | logout | 10min
1    | 2011-01-06 09:50:00 | login  | -

Thanks in advance,

mawo


SELECT x.*, TIMEDIFF(x.logout_date, x.login_date) as duration
FROM
(
SELECT a.user_id, a.`date` as logout_date, 
(SELECT MAX(b.`date`) FROM table1 b WHERE b.`date` <a.`date` 
and b.user=a.user and b.type = 'login') as login_date    
FROM table1 a WHERE a.type ='logout'
)x
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜