0
votes

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.

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.

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')
1
Note that you will also need a condition in the ON clause for "in the current year".Paul Spiegel
Consider handling issues of data display in application codeStrawberry

1 Answers

2
votes

The month() function returns a number, as opposed to the name of the month.

Either use the monthname() function or store the months' number in your helper table as opposed to the name of the month. The latter is slightly more reliable, since the language setting of mysql influences the return value of the monthname() function.