我有一张表(称为" 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来计算每个用户在每个活动上花费的秒数("持续时间"),这是给定日期给定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
我可以让它适用于一系列但不适用于面板。谢谢!
答案 0 :(得分:1)
解决方案包括两次跨越同一个表,一个将对应于发生的“第一个动作”,另一个将对应于“下一个动作”。然后,必要条件可以在查询的“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);
答案 1 :(得分:1)
E.g。类似......
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;