Something like this if in sql server (dont know about mysql);With CTEAS(SELECT ROW_NUMBER() OVER (PARTITION BY accountID, deviceID ORDER BY timestamp) AS Seq,*FROM YourTable)SELECT t.accountID, t.deviceID, t.[timestamp] AS from_timestamp,t1.nexttimestamp AS to_timestampt1.nexttimestamp - t.[timestamp] AS diffFROM CTE tOUTER APPLY (SELECT MIN([timestamp]) AS nexttimestamp FROM CTE WHERE accountID = t.accountID AND deviceID = t.deviceID AND Seq > t.Seq AND speedKPH <> 0 )t1WHERE t.speedKPH = 0AND NOT EXISTS (SELECT 1FROM CTEWHERE accountID = t.accountID AND deviceID = t.deviceIDAND Seq = t.Seq -1AND speedKPH = 0)
Try this and if it doesnt work please post in some mysql forums for more help.------------------------------------------------------------------------------------------------------SQL Server MVPhttp://visakhm.blogspot.com/https://www.facebook.com/VmBlogs