我在mysql中有一个事件表,有两列:UserId,EventTime(datetime)。 我需要为每个UserId计算两件事:
答案 0 :(得分:1)
这是MySQL的痛苦。一种方法使用相关子查询来标识开始,然后使用变量为会话分配编号:
select e.*,
(@s := if(@u <> userid or eventtime > prev_et + interval 2 minute, @s + 1
if(@u := userid, @s, @s)
)
) as session_id
from (select e.*,
(select max(e2.eventtime) from events e2 where e2.userid = e.userid and e2.eventtime < e.eventtime
) as prev_et
from events e
order by userid, eventtime
) e cross join
(select @u := 1, @s := 0) params;