mawo
mawo

Reputation: 219

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 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

Upvotes: 2

Views: 627

Answers (1)

a1ex07
a1ex07

Reputation: 37364

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

Upvotes: 3

Related Questions