mysql - 使用聚合的 SQL 连接
问题描述
我需要编写一个查询,从下面的 3 个表中创建一个简单的报告。(这里的 SQLFiddle:http ://www.sqlfiddle.com/#!9/bec6b9/2 )
表:程序
id | org_id | unique_name
------------------------------
1 15 pg_1
2 25 pg_2
表:客户
id | program_id | first_name | last_name
-------------------------------------------------
1 1 Bob Smith
2 2 John Jones
3 2 Rob Walker
**表:交易**
id | customer_id | amount
---------------------------------
1 1 10.00
2 1 10.00
3 2 10.00
4 2 10.00
5 2 10.00
6 2 10.00
7 3 10.00
8 3 10.00
9 3 10.00
10 3 10.00
我需要生成一个相当简单的报告,说明有多少客户属于每个程序唯一名称,以及每个程序唯一名称的总交易量。
所以对于这个数据,它看起来像......
Program Name | # Customers | Total Amount
-----------------------------------------------
pg_1 1 20.00
pg_2 2 80.00
你可以在这里看到 SQLFiddle:http ://www.sqlfiddle.com/#!9/bec6b9/2
我当前的查询显示了每个客户的交易总额,但我不确定如何将客户分组到一个计数中。
select program.unique_name as "Program Name",
customer.id,
sum(transaction.amount) as "Total Amount"
from program
join customer on customer.program_id = program.id
join transaction on transaction.customer_id = customer.id
group by customer.id
我如何也按程序名称分组?
解决方案
试试下面的。
select p.unique_name, count(distinct c.id), sum(t.amount)
from customer c
left outer join transaction t on t.customer_id = c.id
inner join program p on c.program_id = p.id
group by p.unique_name;
推荐阅读
- android - 是否可以通过创建 AOSP API 代码的副本来使用隐藏方法?
- jestjs - 开玩笑警告:无法对未安装的组件执行 React 状态更新。在 componentDidMount 上
- spring-boot - 如何在 Spring 中绕过 CORS?
- rust - 如何正确地将迭代器传递给 Rust 中的函数
- hyperledger-fabric - Fabric的拜占庭同行下的一致性问题
- json - 从 Wikipedia 转储中读取由 gensim 创建的 JSON 文件
- laravel - 为什么验证器传递错误的请求?
- flutter - Flutter Assertion 调用函数失败
- c - 为什么我不能将二维数组的名称分配给二维指针?
- next.js - ZEIT NOW 变量的秘密