SQL: finding longest date gap

前端 未结 4 1703
面向向阳花
面向向阳花 2020-12-11 04:34

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

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-11 05:02

    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:

    1. Does not return users that have 0 or 1 records.
    2. Does not return users where all records have the same date/time.
    3. Will return multiple records for a user if the user has duplicate records on the starting or ending boundary of their largest gap.

    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.

提交回复
热议问题