每年每个月在MySQL中每个客户的订单计数

时间:2019-03-21 15:06:37

标签: mysql sql

我在MySQL中有3个表,其中有1个客户

______________
customers     | 
______________|
id | name     |
______________|
1  | John     |
2  | Wick     |
______________

然后有2个订单表,每个都是

______________________________________
call_order
______________________________________
id | customer_id | created_at
______________________________________
1  | 1           | 2019-02-19 15:07:48
2  | 2           | 2019-03-19 15:07:48
3  | 1           | 2019-02-19 15:07:48

第二阶表是

______________________________________
direct_order
______________________________________
id | customer_id | created_at
______________________________________
1  | 2           | 2019-02-19 15:07:48
2  | 1           | 2019-03-19 15:07:48
3  | 1           | 2019-02-19 15:07:48

我想要实现的是

____________________________________________
customer | Jan | Feb | Mar | Apr ... | Total
____________________________________________
John     |  0  |  3  |  1  |  0      |  4
Wick     |  0  |  1  |  1  |  0      |  2

我要查询的方式是获取一年中每个月的每个客户的记录,该记录必须按总数排序。这意味着总数最高的客户必须位于顶部。

1 个答案:

答案 0 :(得分:2)

您可以使用union all和条件聚合。像这样:

select c.name,
       sum( month(created_at) = 1 ) as Jan,
       sum( month(created_at) = 2 ) as Feb,
       . . .
       sum( month(created_at) = 12 ) as Dec,
       count(*) as total
from customers c join
     ((select customer_id, created_at
       from call_orders
      ) union all
      (select customer_id, created_at
       from direct_orders
      ) 
     ) o
     on o.customer_id = c.id
group by c.name
order by total desc;

我想您也希望对年份进行限制,所以订单来自同一年而不是多年的同一月。