sql - SQL:使用相等键和最近键连接(类似于 Pandas 的合并)
问题描述
例如,我有 2 个这样的表
对于表 1 中的每一行,我想用
相同
customer id
和最近的
date
(在我的情况下,table2.date < table1.date
)
结果应该是这样的
我怎样才能在 SQL 中做到这一点?我试图搜索,但没有找到很多相关的东西。如果我想将条件更改为<=
,>=
或>
怎么办?
谢谢!
笔记:
- 请使用标准 SQL,因为我没有使用 PostgreSQL
- 如果我可以使用 Python,我可能会简单地使用 for 循环。
解决方案
您可以lateral join
为此使用 a:
select t1.*, t2.* -- choose the columns you want
from table1 t1 left join lateral
(select t2.
from table2 t2
where t2.customer_id = t1.customer_id and
t2.date < t1.date -- do you really mean <= ?
order by t2.date desc
limit 1
) t2;
推荐阅读
- python - 如何在导航到之前修改链接 url
- java - 在创建新的 Java 对象实例时,在匿名代码块中初始化变量是否兼容?
- chef-infra - 这个厨师食谱代码是什么意思
- ms-access - 从 Access 列表框列中获取非重复值
- java - 卡夫卡一次又一次地读取一批消息
- javascript - JS:在 pdfMake 列中创建段落
- db2-400 - 查询 db2 中的所有空表
- android - 如何在 SQLite android 中手动执行检查点?
- django - django - 向用户银行账户转账的最佳方式
- android - Android - RecyclerView 滑动动画不会消失