首页 > 解决方案 > SQL:使用相等键和最近键连接(类似于 Pandas 的合并)

问题描述

例如,我有 2 个这样的表

![在此处输入图像描述

对于表 1 中的每一行,我想用

结果应该是这样的

在此处输入图像描述

我怎样才能在 SQL 中做到这一点?我试图搜索,但没有找到很多相关的东西。如果我想将条件更改为<=,>=>怎么办?

谢谢!

笔记:

标签: sqljoinleft-joinpresto

解决方案


您可以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;

推荐阅读