计算 mysql 中面板数据的时间差

Calculate time difference for panel data in mysql

我有一个 table(称为 "Sessions"),看起来像这样:

user_id | action | datetime  
1       |  1     |  2015-12-06 20:15:46  
1       |  2     |  2015-12-06 20:15:56  
2       |  1     |  2015-12-06 10:01:36  
2       |  2     |  2015-12-06 10:01:39  
1       |  1     |  2015-12-07 18:17:46  
1       |  2     |  2015-12-07 18:17:56  
2       |  1     |  2015-12-07 14:03:46  
2       |  2     |  2015-12-07 14:03:49  

我想使用 mysql 来计算每个用户在每个 activity ("duration") 上花费的秒数,这是给定 [=datetime 之间的差异 user_id 在给定的一天,得到:

user_id |  action |  datetime             | duration  
1       |   1     |   2015-12-06 20:15:46 |      10  
1       |   2     |   2015-12-06 20:15:56 |      NaN  
2       |   1     |   2015-12-06 10:01:36 |      3         
2       |   2     |   2015-12-06 10:01:39 |      NaN 

我可以让它适用于一个系列,但不能用于面板。谢谢!

解决方法是穿过相同的 table 两次,一次对应发生的 "first action",另一次对应 "next action"。然后可以在查询的 "on" 部分表示必要条件:

select first_action.user_id, 
       first_action.action, 
       first_action.datetime,
       (next_action.datetime - first_action.datetime) duration
  from
  (select * from sessions) as first_action 
  left outer join (select * from sessions) as next_action
  on first_action.user_id = next_action.user_id
  and first_action.action + 1 = next_action.action
  and date(first_action.datetime) = date(next_action.datetime);

例如像...

SELECT x.user_id
     , x.action
     , x.datetime start
     , y.datetime stop
     , TIMEDIFF(y.datetime,x.datetime) duration 
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.user_id = x.user_id 
   AND DATE(y.datetime) = DATE(x.datetime) 
   AND y.action = 2 
 WHERE x.action = 1 
 ORDER 
    BY user_id
     , start;