MySQL获取行数并按月分组到列标题

时间:2016-01-05 09:36:29

标签: mysql sql select group-by sum

我有这个结果

Name    |  January  |    Feb    |   March
Adrian  |     12    |           |    
Adrian  |           |     15    |    
Adrian  |           |           |     9
Bryan...

使用此查询

SELECT
    user.first_name AS name,
CASE WHEN MONTH(order.create_datetime) = '1' THEN count(order.id) END AS January,
CASE WHEN MONTH(order.create_datetime) = '2' THEN count(order.id) END AS January,
CASE WHEN MONTH(order.create_datetime) = '3' THEN count(order.id) END AS January
FROM
    order
        JOIN user ON user.id = order.create_by
WHERE
    order.create_datetime BETWEEN '2015-01-01 00:00:00' AND '2015-12-31 23:59:59'
GROUP BY
    order.create_by,
    MONTH(order.create_datetime)
ORDER BY
    user.first_name

我需要它,但我不确定我应该做什么

Name      | January |   Feb   |   March   |TOTAL
Adrian    | 12      |    15   |     9
Bryan

最后一个TOTAL。

提前致谢

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT U.first_name AS NAME,
       SUM(CASE WHEN MONTH(O.create_datetime) = 1 THEN 1 ELSE 0 END) AS January,
       SUM(CASE WHEN MONTH(O.create_datetime) = 2 THEN 1 ELSE 0 END) AS Feb,
       SUM(CASE WHEN MONTH(O.create_datetime) = 3 THEN 1 ELSE 0 END) AS March
FROM ORDER O
JOIN USER U ON U.id = O.create_by
WHERE O.create_datetime BETWEEN '2015-01-01 00:00:00' AND '2015-12-31 23:59:59'
GROUP BY O.create_by
ORDER BY U.first_name

答案 1 :(得分:0)

您需要更改聚合逻辑,如下所示:

SELECT
    user.first_name AS name,
COUNT(CASE WHEN MONTH(order.create_datetime) = '1' THEN (order.id) END) AS JAN,
COUNT(CASE WHEN MONTH(order.create_datetime) = '2' THEN (order.id) END) AS FEB,
COUNT(CASE WHEN MONTH(order.create_datetime) = '3' THEN (order.id) END) AS MAR
FROM
    order
        JOIN user ON user.id = order.create_by
WHERE
    order.create_datetime BETWEEN '2015-01-01 00:00:00' AND '2015-12-31 23:59:59'
GROUP BY
    user.first_name
ORDER BY
    user.first_name
    ;