我有2个表,列在下面
Table1
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上连接两个表,如果值匹配,则停止;如果不在col2上连接,则停止;如果匹配,则在col3上停止否则连接;如果有任何列与else null匹配,则填充val,然后在matchingcol列中填充该列
我可以通过使用左连接来实现这一点。如果有更好的办法,请告诉我。
发布于 2020-03-18 20:03:49
可以使用多个joins:
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
https://stackoverflow.com/questions/60746734
复制相似问题