Generic sql might work:select a.accountid ,a.deviceid ,a.timestamp as timestamp1 ,min(b.timestamp) as timestamp2 ,min(b.timestamp)-a.timestamp as diffstp from eventdata as a left outer join eventdata as b on b.accountid=a.accountid and b.deviceid=a.deviceid and b.timestamp>a.timestamp group by a.accountid ,a.deviceid ,a.timestamp
btw. your output doesn't match your provided sample data (I don't see timestamp 1359088987 anywhere)