简体   繁体   English

如何计算每个月每种客户类型的购买价值?

[英]How to sum purchase value from each customer type each month?

I have two tables.我有两张桌子。

Customers顾客

customer_id客户ID customer_type顾客类型
1 1 student学生
2 2 blue蓝色的

Orders订单

order_id order_id customer_id客户ID purchase_value购买价值 date日期
001 001 1 1 500 500 2021-06-03 2021-06-03
002 002 2 2 600 600 2021-03-01 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 3 0 0 600 600
6 6 500 500 0 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM