填充左连接中表的 NULL 部分

Filling the NULL parts of the tabels in the left join

我有两个具有相似结构的 table,但我需要获取与邮政编码相关的所有信息。

table一个

zip_code    location
1           A
2           C
2           D
3           E
4           F
5           G

tableB

zip_code   location    n
2          A           1
2          C           2
2          D           3
3          A           4
3          E           5
4          F           6
4          H           7
6          Y           8         

如您所见,一个位置可以有多个 zip_code。因此,我必须使用 zip_code 和位置作为连接条件。当我应用 left join 时,我无法填充 NULL 部分。我的填充策略是这样的:

注意:在查看 zip_code 之间的差异时,如果存在它们相等的情况,我想获得较小的数字。例如,就最小差异而言,5 可以得到 4 和 6,但我想选择 4 并查看其他条件。

结果 table 应该是这样的:

zip_code   location    n
1           A          1
2           C          2
2           D          3
3           E          5
4           F          6
5           G          6

我知道这有点复杂,但我可以更详细地解释模糊的部分

这听起来像 OUTER APPLY:

select a.*, b.n
from tableA a outer apply
     (select top (1) b.*
      from tableB b
      order by (case when b.zip_code = a.zip_code and b.location = a.location
                     then -1
                     when b.location = a.location
                     then abs(b.zip_code - a.zip_code)
                     else abs(b.zip_code - a.zip_code)
                end),
               b.n
     ) b;

Here 是一个 db<>fiddle.