I have two tables.
Customers
customer_id | customer_type |
---|---|
1 | student |
2 | blue |
Orders
order_id | customer_id | purchase_value | date |
---|---|---|---|
001 | 1 | 500 | 2021-06-03 |
002 | 2 | 600 | 2021-03-01 |
I want to make a query to show monthly total purchase from each customer type, which is expected to be like this:
month | student | blue |
---|---|---|
3 | 0 | 600 |
6 | 500 | 0 |
I've tried to use subquery like this:
SELECT
month(order_date) as month,
(SELECT sum(order_value) from orders JOIN customers
ON customers.customer_id = orders.customer_id
WHERE customers.customer_type LIKE 'Business'
GROUP BY month, customers.customer_type) as personal
from orders
JOIN customers
ON customers.customer_id = orders.customer_id
But still fail, I want to try to use subquery inside JOIN
but kinda confuse. Do you have any solution to this problem?
Use conditional aggregation:
SELECT MONTH(o.order_date) as month,
SUM(CASE WHEN c.customer_type = 'student' THEN order_value END) as student,
SUM(CASE WHEN c.customer_type = 'blue' THEN order_value END) as blue
FROM orders o JOIN
customers c
ON c.customer_id = o.customer_id
GROUP BY MONTH(o.order_date);
A subquery is unnecessary. Note that using month()
without taking the year to account often produces invalid results.
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.