【问题标题】:The efficient way to use left join to find the closest value使用左连接找到最接近值的有效方法
【发布时间】:2021-10-05 09:18:18
【问题描述】:

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

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,4>
<A,2,4>
<A,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

有没有更好更有效的方法?

【问题讨论】:

  • 所有情况下最接近的值为“4”。我不明白这个问题。
  • 最接近值的定义是什么?在您的简化示例中-很明显!但实际情况是什么 - 你提到你的桌子很大 - 所以你的例子很可能没有呈现真实案例
  • abs(a-b)的最小值
  • 我改变了我的例子,现在更好理解了吗?

标签: sql join google-bigquery left-join cross-join


【解决方案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

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

【讨论】:

  • 很高兴它对你有用,请考虑投票给答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-11-29
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多