简体   繁体   English

按月分组并显示每个月对应的值

[英]Group by a month and display each month to corresponding value

Hi All have query display each month sales by grouping sales based on dates. 大家好,您可以通过按日期对销售额进行分组来查询每个月的销售额。
But i want to display each month beside its sales. 但我想在其销售额旁边显示每个月。 I tried the following query it will return just the sales. 我尝试了以下查询,它将只返回销售。 but no months. 但没有几个月。

SELECT 
CASE 
    WHEN created_at BETWEEN "2012-01-01" and "2012-01-31" THEN "Jan"
    WHEN created_at BETWEEN "2012-02-01" and "2012-02-28" THEN "Feb"
    WHEN created_at BETWEEN "2012-03-01" and "2012-03-31" THEN "Mar"
    WHEN created_at BETWEEN "2012-04-01" and "2012-04-30" THEN "April"
    WHEN created_at BETWEEN "2012-05-01" and "2012-05-31" THEN "May" 
    WHEN created_at BETWEEN "2012-06-01" and "2012-06-30" THEN "June"
    WHEN created_at BETWEEN "2012-07-01" and "2012-07-31" THEN "July"
    WHEN created_at BETWEEN "2012-08-01" and "2012-08-31" THEN "Aug"
    WHEN created_at BETWEEN "2012-09-01" and "2012-09-30" THEN "Sep"
    WHEN created_at BETWEEN "2012-10-01" and "2012-10-31" THEN "Oct"
    WHEN created_at BETWEEN "2012-11-01" and "2012-11-30" THEN "Nov"
    ELSE "Dec" 
END AS "month" , SUM(grand_total) AS total
FROM sales
WHERE created_at >="2012-01-01" AND created_at <="2013-01-01"
GROUP BY TIMESTAMPDIFF(MONTH, "2012-01-01" + INTERVAL 1 DAY, created_at)

How can i display months beside the sales like below. 我如何在如下所示的销售旁边显示月份。

+------+-------+
| Month| Total |
+------+-------+
| Jan  |  1200 |
| Feb  |  5555 |
| Mar  |  1235 | 
| Apr  |  1299 | 
+------+-------+

Thanks in advance. 提前致谢。

Try this: 尝试这个:

SELECT MONTHNAME(created_at) AS month , SUM(grand_total) AS total
FROM sales
WHERE created_at BETWEEN '2012-01-01' AND '2013-01-01'
GROUP BY MONTHNAME(created_at)

Use group by and monthname() : 使用group bymonthname()

SELECT monthname(created_at), SUM(grand_total) AS total
FROM sales
WHERE created_at >= '2012-01-01' AND created_at < '2013-01-01'
GROUP BY monthname(created_at)
order by month(created_at);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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