Mysql 使用最新的数据而不是相等的数据连接SQL
我需要加入2个数据帧使用月份和名称。然而,在其中一个数据帧中,我没有所有的月度结果,所以我想重复最近的一个。 比如说,Mysql 使用最新的数据而不是相等的数据连接SQL,mysql,sql,Mysql,Sql,我需要加入2个数据帧使用月份和名称。然而,在其中一个数据帧中,我没有所有的月度结果,所以我想重复最近的一个。 比如说, Dataframe A name score month Alex 20 2020/01 Alex 30 2020/03 Dataframe B name month tenure Alex 2020/01 1 Alex 2020/02 2 Alex 2020/03 3 Join A+B using name and
Dataframe A
name score month
Alex 20 2020/01
Alex 30 2020/03
Dataframe B
name month tenure
Alex 2020/01 1
Alex 2020/02 2
Alex 2020/03 3
Join A+B using name and month - expected result
name month score tenure
Alex 2020/01 20 1
Alex 2020/02 20 2 --> repeat the score from the most recent date
Alex 2020/03 30 3
有人知道我该怎么做吗?您可以使用相关子查询:
select b.*,
(select a.score
from a
where a.name = b.name and a.month <= b.month
order by a.month desc
limit 1
) as score
from b;
如果您想从数据库中获取多个列,此方法非常方便。MySQL有表,而不是数据帧。欢迎使用SO。请看
select b.*, a.score
from b left join
(select a.*,
lead(month) over (partition by name order by month) as next_month
from a
) a
on b.name = a.name and
b.month >= a.month and
(b.month < a.next_month or a.next_month is null);