首页 > 解决方案 > 将记录与最接近的连接配对

问题描述

我有以下表格:

        id |      detected
-----------+----------------
       288 |       26817612
       288 |       26817734
       468 |       26817609
       468 |       26817646
       476 |       26817700
       502 |       26817609
       502 |       26817616
       502 |       26817655

        id |      fulfilled
-----------+-----------------
       288 |        26817616
       288 |        26817635
       468 |        26817623
       468 |        26817659
       476 |        26817706
       502 |        26817621
       502 |        26817627
       502 |        26817663

我需要做的是通过 id 将这些表加入到表中,将第一个表中的记录与最接近的已完成对应项进行匹配。例如:

id | detected | fulfilled
-------------------------
288| 26817612 | 26817616
288| 26817734 | 26817635
468| 26817609 | 26817623

... 等等。

有什么办法可以用这些数据来做到这一点,还是我在浪费我的时间,应该收集新的?

标签: sqlpostgresql

解决方案


您似乎也想减少行数。对我来说,这表明row_number()

select t12.*
from (select t1.*, t2.*fulfilled
             row_number() over (partition by t1.id order by abs(t1.detected - t2.fulfilled)) as seqnum
      from t1 join
           t2
           on t1.id = t2.id
     ) t12
where seqnum = 1;

推荐阅读