【问题标题】:Joins based on condition on columns基于列条件的联接
【发布时间】:2020-03-18 20:00:18
【问题描述】:

我有 2 个表格,下面是列

表1

col1   col2   col3     val
 11     221     38      10
null    90      null     989
78     90       null     77

表2

col1   col2   col3  
 12     221    78
 23     null   67 
 78      90     null

我想要这样的输出

col1   col2   col3     val     matchingcol
 11     221     38      10       col2
null    90      null     null      null
78     90       null     77       col1

如果值匹配,我想在第一个 col1 上加入 2 个表,如果匹配则在 col2 上不加入,如果匹配,则停止 else 加入 col3 并填充 val,如果任何列匹配 else null 并且任何匹配的列然后在matchingcol 中填充该列专栏

我可以通过使用左连接来实现这一点。如果有更好的方法请告诉我

【问题讨论】:

  • 你有没有试过???
  • 是的,我使用左连接得到了我想要的结果,但我正在寻找比左连接更好的解决方案
  • 所以发布您的查询。

标签: sql impala


【解决方案1】:

您可以使用多个连接:

select t1.*,
       (case when t2_1.col1 is not null then 'col1'
             when t2_1.col2 is not null then 'col2'
             when t2_1.col3 is not null then 'col3'
        end) as matchingcol
from table1 t1 left join
     table2 t2_1
     on t2_1.col1 = t1.col1 left join
     table2 t2_2
     on t2_2.col2 = t1.col2 and t2_1.col1 is null left join
     table2 t2_3
     on t2_3.col3 = t1.col3 and t2_2.col2 is null

【讨论】:

  • when t2_2.col2 -- 在第二种情况下。第三种情况也是如此。
  • 我对连接部分做了同样的事情,但是 matchcol sld 不仅基于非 null 填充,而且两个表中的 col 都匹配
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-15
  • 2022-11-27
  • 2021-11-16
  • 1970-01-01
  • 2018-06-13
  • 2019-11-21
  • 1970-01-01
相关资源
最近更新 更多