必须通过另一个 table 检查的案例陈述

Case statement that has to check through another table

我有 table t1:

pers_key  code1  code2
       1     AA     BB
       2     AA     CC
       3     AA     DD
       4     BB     CC
       5     BB     DD
       6     CC     DD     

还有一个 table t2:

code  ind_A  ind_B  ind_C
  AA      1      0      0
  BB      0      1      0
  CC      0      0      1
  DD      1      0      1

我想将这些 table 连接在一起,以便对于 t1 中的每条记录,我们添加列 ind_A、ind_B、ind_C 并将它们设置为 1如果相应的代码指定它。例如,这将是我理想的输出 table:

pers_key  code1  code2  ind_A  ind_B  ind_C
       1     AA     BB      1      1      0
       2     AA     CC      1      0      1
       3     AA     DD      1      0      1
       4     BB     CC      0      1      1 
       5     BB     DD      1      1      1
       6     CC     DD      1      0      1

因此,对于每个 t1 记录,如果其 code1 或 code2 在另一个 table t2 中的 inds 为 1,我们将 inds 设置为 1。实现此结果的最佳方法是什么?请记住,这只是获取 idea/method 的示例,在我的实际数据中有数百个不同的代码值。我正在使用 HIVE/hiveQl 版本 0.12。

Hive 不支持 SELECT 子句中的子查询。但是,您可以使用连接来做到这一点:

select t1.*,
       (case when t2a.ind_A = 1 or t2b.ind_A = 1 then 1 else 0 end) as ind_A,
       (case when t2a.ind_B = 1 or t2b.ind_B = 1 then 1 else 0 end) as ind_B,
       (case when t2a.ind_C = 1 or t2b.ind_C = 1 then 1 else 0 end) as ind_C
from t1 left join
     t2 t2a
     on t1.code1 = t2a.code left join
     t2 t2b
     on t1.code2 = t2b.code;

注意:即使代码不匹配 t2

,这也应该有效