I understand that you want to ignore consecutive logins, and only consider the last one.
You can use window functions. Here are two approaches using lag()
, available in MySQL 8.0.
If a logout is always preceded by a login, you can do:
select username,
count(*) as cnt_sessions,
sum(event_epoch_time - lag_event_epoch_time) as sum_session_duration
from (
select t.*,
lag(event_epoch_time) over(partition by username order by event_epoch_time) as lag_event_epoch_time
from mytable t
) t
where event = 'logout'
group by username
We can also tweak the query so it ignores consecutive logouts:
select username, sum(event_epoch_time - lag_event_epoch_time) as diff
from (
select t.*,
lag(event_epoch_time) over(partition by username order by event_epoch_time) as lag_event_epoch_time,
lag(event) over(partition by username order by event_epoch_time) as lag_event
from mytable t
) t
where event = 'logout' and lag_event = 'login'
group by username
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…