[英]Hive table join with update
I am a bit stuck , Can any one help me here. 我有点卡住,任何人都可以在这里帮助我。 I have two tables with the below structure. 我有两个具有以下结构的表。
Table 1
Id String
Code1 String
Code2 String
Table 2
Id String
UserCode String
UniversalCode String
What i need to do is to replace all value in code1 and code2 with UniversalCode from the table 2. To be more clear , if code1 matches UserCode then repalce Code1 with universalCode and again for the same record if code2 matches with usercode then replace it with UniversalCode. 我需要做的是用表2中的UniversalCode替换code1和code2中的所有值。更明确地说,如果code1与UserCode匹配,则用UniversalCode替换Code1;如果code2与usercode匹配,则再次对同一条记录替换,然后替换为通用代码。 If there is no match retain the value for code1 and code2. 如果不匹配,则保留code1和code2的值。 I need to have all records from table 1. Table 1 and Table 2 are connected via Id. 我需要具有表1中的所有记录。表1和表2通过ID连接。
I tried the below for one column but got stuck adding code2 我在下面尝试了一列,但在添加代码2时卡住了
SELECT
Id,
CASE WHEN a.Code1 = b.UserCode then b.UniversalCode else a.Code1 end
from table1 a
LEFT OUTER JOIN table2 b ON (a.Id = b.Id and a.code1 = b.UserCode);
Any suggestions to get this done ? 有什么建议可以做到这一点吗? , The real scenario has 5-6 columns where i need to apply the same logic. ,实际情况有5-6列,我需要应用相同的逻辑。
Test Data
Table 1
1,123,ABCD
1,ABCD,123
1,456,BCD
1,BCD,789
1,789,100
Table 2
1,123,XXX
1,456,YYY
1,789,ZZZ
2,123,XXX
2,456,YYY
2,789,ZZZ
Output
1,XXX,ABCD
1,ABCD,XXX
1,YYY,BCD
1,BCD,ZZZ
1,ZZZ,100
output with a.id=b.id in Join(Please refer below comments for this output)
1 123 XXX 100 100
1 123 123 100 100
1 123 123 100 100
1 ABCD ABCD 101 101
1 ABCD ABCD 101 101
1 ABCD ABCD 101 101
1 456 456 DEF DEF
1 456 YYY DEF DEF
1 456 456 DEF DEF
1 BCD BCD 789 789
1 BCD BCD 789 789
1 BCD BCD 789 ZZZ
1 789 789 CDE CDE
1 789 789 CDE CDE
1 789 ZZZ CDE CDE
1 100 100 HBT HBT
1 100 100 HBT HBT
1 100 100 HBT HBT
1 100 100 123 XXX
1 100 100 123 123
1 100 100 123 123
I'm not sure if I understand you but something like this should help you. 我不确定我是否了解您,但类似的方法应该可以为您提供帮助。
SELECT
a.Id
, CASE WHEN a.Code1 = b.UserCode THEN b.UniversalCode ELSE a.Code1 END AS Code1
, CASE WHEN a.Code2 = b.UserCode THEN b.UniversalCode ELSE a.Code2 END AS Code2
FROM table1 a
LEFT OUTER JOIN
table2 b
ON a.Id = b.Id;
We can try the below query:- 我们可以尝试下面的查询:
SELECT
Id,
CASE WHEN Code1 = UserCode then UniversalCode else Code1 end,
CASE WHEN Code2= UserCode then UniversalCode else Code2 end
from
(select a.id,a.Code1,a.Code2,b.UserCode,b.UniversalCode
from table1 a
LEFT OUTER JOIN table2 b ON (a.Id = b.Id and a.code1 = b.UserCode) union
select a.id,a.Code1,a.Code2,b.UserCode,b.UniversalCode
from table1 a
LEFT OUTER JOIN table2 b ON (a.Id = b.Id and a.code1 = b.UniversalCode)) dat ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.