您好所有人都会根据日期对销售进行分组来显示每个月的销售情况 但是我想在每个月的销量旁边展示一下。 我尝试了以下查询,它将只返回销售。但没有几个月。
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)
如何在销售旁边显示月份,如下所示。
+------+-------+
| Month| Total |
+------+-------+
| Jan | 1200 |
| Feb | 5555 |
| Mar | 1235 |
| Apr | 1299 |
+------+-------+
提前致谢。
答案 0 :(得分:2)
试试这个:
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)
答案 1 :(得分:1)
使用group by
和monthname()
:
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);