Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 带聚合的SQL连接_Mysql_Sql_Join_Aggregate Functions - Fatal编程技术网

Mysql 带聚合的SQL连接

Mysql 带聚合的SQL连接,mysql,sql,join,aggregate-functions,Mysql,Sql,Join,Aggregate Functions,我需要编写一个查询,从下面的3个表中创建一个简单的报告。(这里是SQLFiddle:) 表格:程序 id | org_id | unique_name ------------------------------ 1 15 pg_1 2 25 pg_2 表格:客户 id | program_id | first_name | last_name ------------------------------

我需要编写一个查询,从下面的3个表中创建一个简单的报告。(这里是SQLFiddle:)

表格:程序

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
您可以在这里看到SQLFIDLE:

我当前的查询显示了每个客户的交易总额,但我不确定如何将客户分组到计数中

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;

在您添加另一个没有交易的客户之前,这一切都很好。如果我将第三个客户添加到pg#2程序并运行您的查询,它仍然在“#Customers”中显示2而不是3,因为客户id不在事务表中。嗨,Scott,非常正确,我已更新查询以处理该场景