如何在mysql中按列计算多个组?

时间:2017-03-19 04:28:43

标签: mysql sql group-by

首先,我们说我有一张用户订单表。

例如:

| user_id | created_at | order_data |
| ------- | ---------- | ---------- |
|   1     | 2010-01-02 |   {data}   |
|   2     | 2010-02-04 |   {data}   |
|   1     | 2011-01-02 |   {data}   |
|   3     | 2011-01-02 |   {data}   |
|   1     | 2011-04-02 |   {data}   |

现在,我想计算每年的每个月,发生了多少订单。比如,2010年,01月,计数1个订单; 2010年,02月,1个订单,2011年01个月,2个订单......

3 个答案:

答案 0 :(得分:0)

您可以从created_at中提取年份和月份,然后对其执行聚合。

select year(created_at) yr,
    month(created_at) mon,
    count(*) no_of_orders
from your_table
group by year(created_at),
    month(created_at)

答案 1 :(得分:0)

    SELECT YEAR(CREATED_AT) AS YEAR,
           MONTH(CREATED_AT) AS MONTH,
           COUNT(*) AS NUM_OF_ORDERS
      FROM ORDERS
    GROUP BY YEAR(CREATED_AT), MONTH(CREATED_AT);

答案 2 :(得分:0)

您需要从“Created_at”列中提取年份和月份,然后对它们执行聚合

select year(created_at) as year,
       month(created_at) as month,
       count(*) as no_of_orders
from order_table
group by year(created_at),
         month(created_at)