【问题标题】:SQL Nested Joins (Case Statement and Join)SQL 嵌套联接(Case 语句和联接)
【发布时间】:2020-12-01 11:46:30
【问题描述】:

Hive DBMS;两张表——A和B

表 A

prnt_id      sub_id      ac_nm      cost    units
unknown      abc01       abc corp   34500   24
unknown      unknown     xyz corp   9800    10
856          abc03       jfk corp   9820    12

表 B

prnt_id      sub_id      ac_nm 
123          abc01       abc corp
456          abc02       xyz corp
856          abc03       jfk corp
859          abc04       ops corp

问题 --> 尝试执行以下查询: 将表 A 与表 B 连接,首先在 prnt_id 上,如果是“未知”,然后在 sub_id 上连接,如果是“未知”,在 ac_nm 上连接

期望的输出

prnt_id      sub_id      ac_nm      cost    units
123          abc01       abc corp   34500   24
456          abc02       xyz corp   9800    10
856          abc03       jfk corp   9820    12

【问题讨论】:

  • 提供样本数据和期望的结果。
  • 什么是unknown?你的意思是null
  • 不,未知是字符串值,也可能是NULL,两种情况都可能存在。

标签: sql hadoop join hive case


【解决方案1】:

您必须使用TableBLEFT 连接到TableA 的3 个副本并过滤掉不匹配的行:

select b.*,
       coalesce(a1.cost, a2.cost, a3.cost) cost,
       coalesce(a1.units, a2.units, a3.units) units
from TableB b
left join TableA a1 on a1.prnt_id = b.prnt_id
left join TableA a2 on a2.sub_id = b.sub_id and a1.prnt_id is null
left join TableA a3 on a3.ac_nm = b.ac_nm and a2.sub_id is null
where coalesce(a1.prnt_id, a2.sub_id, a3.ac_nm) is not null
order by b.prnt_id

请参阅demo
结果:

| prnt_id | sub_id | ac_nm    | cost  | units |
| ------- | ------ | -------- | ----- | ----- |
| 123     | abc01  | abc corp | 34500 | 24    |
| 456     | abc02  | xyz corp | 9800  | 10    |
| 856     | abc03  | jfk corp | 9820  | 12    |

【讨论】:

    【解决方案2】:

    您可以使用left joins 和coalesce() 选择第一个匹配项:

    select a.*, coalesce(b.?, bs.?, ba.?) as new_col
    from a left join
         b
         on b.prnt_id = a.prnt_id left join
         b bs
         on bs.sub_id = a.sub_id and b.prnt_id is null left join
         b ba
         on bs.ac_nm = a.ac_num and bs.sub_id is null;
    

    【讨论】:

      猜你喜欢
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 2017-03-24
      • 2012-03-25
      • 1970-01-01
      相关资源
      最近更新 更多