使用左连接找到最接近值的有效方法

问题描述

我需要在右表中找到最接近的值并将它们组合起来。 但是为了做到这一点,我的左连接查询在所有排列上运行,它需要大量资源来计算(我的基本表很大)

For example my A table looks like 
<A,1>
<A,2>
<A,10>

And table B looks like : 

<A,4>
<A,5>
<A,6>
<A,7>

For this example the result will be: 

<A,1,2,10,7>

我是这么想的:

select * from (
select *,row_number() over(partition by rown order by abs(b-a) asc)  diff  from (
(select a,b,row_number over () rown from x) a
CROSS JOIN
(select a,b from x) b
on a.a = b.a

) )where diff =1

有没有更好更有效的方法来做到这一点?

解决方法

考虑下面的例子

select id,a.val a_val,b.val b_val
from tableA a
left join tableB b
using(id)
where true 
qualify row_number() over(partition by id,a.val order by abs(a.val - b.val)) = 1

如果应用于您问题中的样本数据 - 输出为

enter image description here

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...