首页 > 解决方案 > 添加包含总计的汇总列

问题描述

我想使用 SQL 从表 (a) 中的原始数据进行查询并将总计的汇总列添加到单个表 (b) 中。

请参考示例。表 b 是我想要的查询结果。

有人可以帮忙吗?谢谢你。

例子

标签: sqlhiveaggregation

解决方案


尝试使用Join,根据您的示例,我们称之为test

Select table1.user, table1.restaurant, table1.spendings, table2.total_spendings
FROM
    (
        SELECT user, restaurant, sum(spending) AS spendings
        FROM test
        GROUP BY user, restaurant
    ) table1
JOIN
    (
        SELECT user, sum(spending) AS total_spendings
        FROM test
        GROUP BY user
    ) table2
ON table1.user = table2.user;

推荐阅读