sql - 添加包含总计的汇总列
问题描述
我想使用 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;
推荐阅读
- abap - 在外向交货处理时捕获过帐发货事件
- ansible - Ansible 复制模块需要很长时间才能跨多台机器复制文件
- kotlin - Kotlin - 在迁移到 Kotlin 1.3 后,协程会导致 DefaultDispatcher 占用大量 CPU
- windows - Windows 2012 上的 Ansible 2.7 不接受 /norestart 选项
- mysql - MySql 服务器的 Azure 数据库的服务器管理员用户访问权限丢失
- reactjs - ReactJS:单击项目时的返回值(多步形式)
- javascript - 在 PHP 中使用分辨率的移动重定向
- java - 在自定义启动器中访问 spring 应用程序名称
- javascript - 使用AngularJS计算总量
- html - 在灵活高度的内容框上悬停设置宽度