[英]Add a summary column with totals
我想使用 SQL 从表 (a) 中的原始数据进行查询并将总计的汇总列添加到单个表 (b)。
请参考示例。 表 b 是我想要的查询结果。
有人可以帮忙吗? 谢谢你。
尝试使用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;
尝试创建视图(虚拟表) - 创建视图的代码
CREATE VIEW VIEW_NAME
AS SELECT COUNT(*)
FROM TABLE_A;
您想要 window 功能:
select user, restaurant, sum(spending) as spending,
sum(sum(spending)) over () as total_spending
from t
group by user, restaurant;
如果要将其插入到新表中,可以使用create table as
或insert
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.