Mysql 基于不使用变量的列获取下一行的值
我有一个数据库,跟踪用户采取的行动。我要做的是创建一个新列(follow_up),该列根据用户在会话期间采取的下一个操作(即会话中的下一个事件id)进行填充。不幸的是,我没有能力使用或创建变量-这显然使这更复杂,因为我无法创建一个行号变量 我的数据如下所示:Mysql 基于不使用变量的列获取下一行的值,mysql,sql,mysql-workbench,Mysql,Sql,Mysql Workbench,我有一个数据库,跟踪用户采取的行动。我要做的是创建一个新列(follow_up),该列根据用户在会话期间采取的下一个操作(即会话中的下一个事件id)进行填充。不幸的是,我没有能力使用或创建变量-这显然使这更复杂,因为我无法创建一个行号变量 我的数据如下所示: Session ID | Event_ID | Action 1 | 1 | Action A 1 | 2 | Action B 2 | 3
Session ID | Event_ID | Action
1 | 1 | Action A
1 | 2 | Action B
2 | 3 | Action A
1 | 4 | Action C
2 | 5 | Action C
2 | 6 | Action A
3 | 7 | Action B
1 | 8 | Action A
2 | 9 | Action C
3 | 10 | Action C
我希望我的最终数据集是:
Session_ID | Event_ID | Action | Follow_Up
1 | 1 | Action A | Action B
1 | 2 | Action B | Action C
2 | 3 | Action A | Action C
1 | 4 | Action C | Action A
2 | 5 | Action C | Action A
2 | 6 | Action A | Action C
3 | 7 | Action B | Action C
1 | 8 | Action A | Null
2 | 9 | Action C | Null
3 | 10 | Action C | Null
提取这些数据的代码非常简单。事实证明,添加后续列很困难假设
事件Id
是唯一且递增的,您可以得到如下后续列:
select
t.*,
(
select Action from tablename
where Event_Id = (
select min(Event_Id) from tablename
where Session_id = t.Session_id and Event_id > t.Event_id
)
) Follow_Up
from tablename t
请参阅。
结果:
“跟进”列根据用户在会话期间采取的下一个操作(即使用子查询的会话中的下一个事件id)进行填充
select
Session_ID,
Event_ID ,
Action,
(select Action from test t1
where t1.Event_ID>t.Event_ID and t1.Session_ID=t.Session_ID
limit 1) Follow_up
from test t;
select
Session_ID,
Event_ID ,
Action,
(select Action from test t1
where t1.Event_ID>t.Event_ID and t1.Session_ID=t.Session_ID
limit 1) Follow_up
from test t;