I have a single MySQL table with login data of users.
user | date | type -----+---------------------+------ 1 | 2011-01-05 08:00:00 | login
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`