SQL连接与聚合

时间:2018-12-18 00:46:19

标签: mysql sql join aggregate-functions

我需要编写一个查询,该查询从下面的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 

我需要生成一个相当简单的报告,说明每个程序unique_name属于多少个客户,以及每个程序唯一名称的总交易额。

因此对于这些数据,看起来就像...

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

如何同时对程序名称进行分组?

1 个答案:

答案 0 :(得分:2)

尝试以下。

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;