基于列条件的连接

问题描述 投票:0回答:1

我有2个表,下面的列

表1

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

table2

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上不连接,则停止,如果匹配停止,否则在col3上连接,如果任何列匹配的则为null,否则填充val,然后匹配的列将在matchingcol列中填充该列

我可以通过使用left joins实现此目的。请让我知道是否有更好的方法

sql impala
1个回答
0
投票

您可以使用多个联接:

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
© www.soinside.com 2019 - 2024. All rights reserved.