scott80109
scott80109

Reputation: 381

SQL join with aggregates

I need to write a query that creates a simple report from the 3 tables below. (SQLFiddle here: http://www.sqlfiddle.com/#!9/bec6b9/2)

Table : Program

id    |  org_id  |  unique_name
------------------------------
1        15         pg_1
2        25         pg_2

Table: Customer

id    |  program_id   |  first_name  |  last_name
-------------------------------------------------
1        1               Bob            Smith
2        2               John           Jones
3        2               Rob            Walker

**Table: Transaction **

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 

I need to generate a fairly simple report of how many customers belong to each program unique_name, and the total transaction amount for each program unique name.

So for this data, it would look like...

Program Name   |  # Customers    | Total Amount
-----------------------------------------------
pg_1              1                 20.00
pg_2              2                 80.00

You can see the SQLFiddle here: http://www.sqlfiddle.com/#!9/bec6b9/2

My current query shows the transaction total for each customer, but I'm not sure how to group the customers into a count.

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

How do I also group on program name?

Upvotes: 1

Views: 72

Answers (1)

Shaun Peterson
Shaun Peterson

Reputation: 1790

try the below.

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;

Upvotes: 2

Related Questions