【发布时间】:2020-12-23 22:11:41
【问题描述】:
我有一张这样的桌子t1:
store_id industry_id cust_id amount gender age
1 100 1000 1.00 M 20
2 100 1000 2.05 M 20
3 100 1000 3.15 M 20
4 200 2000 5.00 F 30
5 200 2000 6.00 F 30
还有一张桌子t2,看起来像这样:
store_id industry_id cust_id amount
10 100 1000 10.00
20 200 2000 11.00
假设我们要构建一个表格,其中包含每个行业中给定客户的所有交易。换句话说,是这样的:
store_id. industry_id. cust_id. amount
1 100 1000 1.00
2 100 1000 2.05
3 100 1000 3.15
4 200 2000 5.00
5 200 2000 6.00
10 100 1000 10.00
20 200 2000 11.00
我试图通过在下面的查询中使用 join 和 coalesce 语句来做到这一点,但它不起作用,因为每一行都有一个 t1 中的 amount 列的条目,即有'没有任何 NULL 值供 coalesce 语句使用。使用联接执行此操作的最佳方法是什么?
SELECT
a.store_id,
a.industry_id,
a.cust_id,
COALESCE(a.amount,b.amount,0) AS amount
FROM t1 a
LEFT JOIN (SELECT store_id AS store_id_2, industry_id AS industry_id_2, cust_id AS cust_id_2, amount FROM t2) b
ON a.cust_id=b.cust_id_2 AND a.industry_id=b.industry_id_2;
此查询结果:
store_id industry_id cust_id amount
1 100 1000 1.00
2 100 1000 2.05
3 100 1000 3.15
4 200 2000 5.00
5 200 2000 6.00
【问题讨论】:
标签: sql hive union hiveql full-outer-join