[英]How to sum purchase value from each customer type each month?
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.但仍然失败,我想尝试在
JOIN
中使用子查询,但有点困惑。 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.请注意,使用
month()
而不考虑年份通常会产生无效结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.