SQL time difference within single table
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,
mawoSELECT 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
精彩评论