简体   繁体   English

SQL查询可计算并显示一年中每个月的总计数据

[英]SQL query calculate and display sum data per each month of the year

I have 'orders' table with some data like the following: 我有一些数据的“订单”表,如下所示:

---------------------------------
id     |   amount  |  order_date   
---------------------------------
1      |   100.00  |  2018-03-12
2      |   120.00  |  2018-03-25
3      |   200.00  |  2018-04-10
4      |   250.00  |  2018-04-20
5      |   300.00  |  2018-05-02

i want to display the SUM('amount') per each month in the current year, i want to use this data to create a chart later. 我想显示当前年份每个月的SUM('amount'),我想稍后使用此数据创建图表。

I want to achieve like this results. 我想要达到这样的结果。

---------------------------------
month        |   sum(amount)
---------------------------------
January      |   0.00  
February     |   0.00 
March        |   320.00 
April        |   450.00
Mai          |   300.00
June         |   0.00
July         |   0.00
August       |   0.00
September    |   0.00
October      |   0.00
November     |   0.00
December     |   0.00

I create a separate table 'months' containing all the months of the year then i left join 'orders' with it but it didn't work, this is the query i use. 我创建了一个单独的表“ months”,其中包含一年中的所有月份,然后我将其与“ orders”保留在一起,但没有用,这是我使用的查询。

Please help. 请帮忙。

SELECT months.month, IFNULL( sum(orders.amount), 0 ) AS amount
FROM months
LEFT OUTER JOIN orders ON month(orders.order_date) = months.month
GROUP BY months.month


update 更新

Finally i made it work this is my query 最后我使它工作这是我的查询

SELECT IFNULL( sum(orders.amount), 0 ) AS amount
FROM months
LEFT OUTER JOIN orders ON monthName(orders.order_date) = months.month
GROUP BY months.month
Order BY FIELD(MONTH,'January','February','March','April', 'May', 'June', 'Jully', 'August', 'September', 'October', 'November', 'December')

The month() function returns a number, as opposed to the name of the month. month()函数返回一个数字,而不是月份的名称。

Either use the monthname() function or store the months' number in your helper table as opposed to the name of the month. 使用monthname()函数或将月份的数字(而不是月份的名称存储在助手表中。 The latter is slightly more reliable, since the language setting of mysql influences the return value of the monthname() function. 后者稍微可靠一些,因为mysql的语言设置会影响monthname()函数的返回值。

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

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