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

MySQL中每个客户每年每月的订单计数,mysql,sql,Mysql,Sql,我在MySQL中有3个表,其中一个有客户 ______________ customers | ______________| id | name | ______________| 1 | John | 2 | Wick | ______________ 然后是两个订单表,每个都是 ______________________________________ call_order _____________________________________

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

______________
customers     | 
______________|
id | name     |
______________|
1  | John     |
2  | Wick     |
______________
然后是两个订单表,每个都是

______________________________________
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

我想以一种方式进行查询,以获得每年每个月的每个客户的记录,这些记录必须按总数排序。这意味着总金额最高的客户必须位于顶部。

您可以使用
联合所有人和条件聚合。大概是这样的:

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;

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

您可以使用
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;

我想你也希望限制一年,所以订单是从同一个月,而不是同一个月在多个年份。

你实际的查询是什么?认真考虑在应用程序代码中显示数据的问题,什么是你的实际查询?认真考虑应用程序代码中的数据显示问题。