I have a table with 2 fields: unique ID, user ID (foreign key) and date-time. This is an access-log to a service. I work in SQL Server but I would appreciate agnostic answer
First, join the table to itself so each record for a given user is paired with any record for that same user.
Then, select only those pairs where the first is before the last, there is no record before the first one, and no record after the last one.
SELECT t1.id, t1.[user-id], t1.time, (t2.time - t1.time) AS GapTime
FROM
t AS t1
INNER JOIN t AS t2 ON t1.[user-id] = t2.[user-id]
WHERE
t1.time < t2.time
AND NOT EXISTS (SELECT NULL FROM t AS t3 WHERE t3.[user-id] = t1.[user-id]
AND t3.time > t2.time)
AND NOT EXISTS (SELECT NULL FROM t AS t4 WHERE t4.[user-id] = t1.[user-id]
AND t4.time < t1.time)
Caveats:
If desired, you can fix #2 above by changing "t1.time < t2.time" to "t1.time <= t2.time", which will give you a gap of 0 if there is only one record for the user.