聚合不同表中的金额

mum43rcc  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(341)

我有一张table 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

还有一张table 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语句来实现这一点,但是它不起作用,因为每一行都有一个 amount 中的列 t1 ,即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
j91ykkif

j91ykkif1#

对于此数据集 union all 似乎很好:

select store_id, industry_id, cust_id, amount from t1
union all
select store_id, industry_id, cust_id, amount from t2

我推测相同的store/industry/customer元组可能出现在这两个表中,您只需要结果中的一行和相应的金额之和。如果是这样,你可能会对 full join :

select
    coalesce(t1.store_id, t2.store_id) store_id,
    coalesce(t1.industry_id, t2.industry_id) industry_id,
    coalesce(t1.cust_id, t2.cust_id) cust_id,
    coalesce(t1.amount, 0) + coalesce(t2.amount, 0) amount
from t1
full join t2 
    on t2.store = t1.store and t2.industry = t1.industry and t2.cust_id = t1.cust_id

相关问题