I'm struggling with this JOIN + SUM query
What I have are these following tables (Client, orders, product)
client_id | name |
---|---|
1 | Frank |
2 | Emile |
3 | Rose |
4 | Laura |
5 | Samuel |
order_number | client_id | product_id | units_sold |
---|---|---|---|
1 | 4 | 1 | 11 |
2 | 3 | 2 | 8 |
3 | 5 | 3 | 18 |
4 | 4 | 4 | 19 |
5 | 3 | 5 | 12 |
product_id | description | price |
---|---|---|
1 | Rice | 26.10 |
2 | Coffee | 12.50 |
4 | Sugar | 13 |
5 | Beans | 5.40 |
3 | Milk | 30.00 |
What I'm trying to do is generate a query that shows the ID and name of each customer and the total sum (sum of quantity of products purchased).
So far, my logic without breaking it is this:
Select
c.client_id, c.first_name
from client c
INNER JOIN orders o on o.client_id = c.client_id
I want to add the SUM part to it but whenever I try it, the new query line doesn't work
If you just want the sum of quantity of products:
SELECT c.client_id, c.first_name, SUM(o.units_sold)
FROM
client c
INNER JOIN orders o ON o.client_id = c.client_id
GROUP BY c.client_id, c.first_name;
But if you also want to see the price:
SELECT c.client_id, c.first_name, SUM(o.units_sold),
SUM(o.units_sold*p.price)
FROM
client c
INNER JOIN orders o ON o.client_id = c.client_id
INNER JOIN products p ON o.product_id = p.product_id
GROUP BY c.client_id, c.first_name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.