【问题标题】:Aggregating Amounts from Different Tables汇总来自不同表的金额
【发布时间】: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


    【解决方案1】:

    对于这个数据集union all 似乎已经足够好了:

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

    我推测同一个商店/行业/客户元组可能会出现在两个表中,并且您只需要结果中的一行以及相应金额的总和。如果是这样,您可能对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
    

    【讨论】:

    • 谢谢。这确实是一个更大查询的 sn-p。这可以通过左连接实现吗?
    • @Caerus:对于您的样本数据,left join 不合适。您在两个表中都有不属于另一个表的行。
    猜你喜欢
    • 2019-07-22
    • 2017-07-11
    • 1970-01-01
    • 2021-02-13
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-08
    相关资源
    最近更新 更多