[英]Build an adjacency list from timeseries data in SQL
假设我在 mysql 数据库中有以下数据:
table
例如,如果数据如下所示:
timestamp event session_id
2014-01-01 01:01:02 Login 1234
2014-01-01 01:01:03 Like 1234
2014-01-01 01:01:05 Logout 1234
要得到这样的结果:
session_id from_event event
1234 null Login
1234 Login Like
1234 Like Logout
我在想的是把事件作为一个有序数组:
select session_id, group_concat(event order by timestamp)
from table
group by session_id
但是从那里不确定我将如何构建邻接列表(在 sql 中)。
If you are running MySQL 8.0, you can just use window function lag()
to get the "previous" event of the same session:
select
session_id,
lag(event) over(partition by session_id order by timestamp) from_event,
event
from mytable
在早期版本中,一种替代方法是相关子查询:
select
session_id,
(
select t1.event
from mytable t1
where t1.session = t.session and t1.timestamp < t.timestamp
order by t1.timestamp desc
limit 1
) from_event,
event
from mytable t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.