tags:

views:

44

answers:

1

I have data in an SQLite table that looks like this:

user_id     event_date
----------  ----------
1000001     2008-01-01
1000001     2008-03-13
1000001     2008-07-04
1000002     2007-01-06
1000002     2008-01-01
1000002     2009-06-01
1000002     2010-12-11

For each of the user_ids I would like to select the largest time gap between pairs of consecutive event_dates. For example in this particular data, user 1000001 has two gaps: 72 days between 2008-01-01 and 2008-03-13, and 113 days between 2008-03-13 and 2008-07-04, so the query should output 113 for user 1000001. User 1000002 has three gaps; largest is 558 days.

Is this possible? Would I have to pre-calculate the time spans and store them with the data, or select everything and post process? I'd like to be able to get it done directly with only the data as shown and directly in the database. Am I abusing SQL by expecting it to be able to treat this data as a list?
Thanks.

+1  A: 

If you can not change the data-model, you could use:

SELECT user_id, MAX(event_date - prior_event_date)
  FROM (SELECT t.user_id, t.event_date, MAX(prior.event_date) AS prior_event_date
          FROM your_table AS t
               JOIN your_table AS prior ON (t.user_id=prior.user_id
                                            AND prior.event_date < t.event_date)
         GROUP BY t.user_id, t.event_date) AS events
 GROUP BY user_id;

If you want 0s to be included use a LEFT JOIN.

Robert Kluin
Beauty, thanks. Works perfectly.
Dave