Skip to content
Advertisement

MySQL = Grouping Sales Count by Months, then Displaying months as Names (Jan, Feb…DEC) not Numerical Value (1,2,3-12)

This seems like a reasonably simple problem but I cannot figure out how to change a numerical value of a month into the months actual name after the sales count is grouped by the month.

Basically I want to list the total amount of sales for each month. Currently this is what I have:

SELECT MONTH(SaleDate) as "Month", Count(*) as "TotalSales"
FROM Sale
GROUP BY MONTH(SaleDate);

This works great for what I want to do. And gives this results:

+---------------------------------+
|     Month      |   TotalSales   |
+---------------------------------+
|       1        |       123      |
|       2        |       142      |
|       3        |       183      |
|       4        |       99       |
|       5        |       127      |
|       6        |       202      |
+---------------------------------+
etc....

However I want the list to have the months as January, February…etc.

I’ve tried multiple ways using MONTHNAME(), MONTHNAME(STR_TO_DATE) and many others, but grouping the months seems to cause the issue.

I feel like I’m missing a very simple solution but am unable to find any online. For reference the dates in the Sale table are default (2017-01-01 or YYYY-MM-DD). And the sale table has three attributes: SaleID, StoreID and SaleDate.

+---------------------------------+
|     Month      |   TotalSales   |
+---------------------------------+
|    January     |       123      |
|    February    |       142      |
|     March      |       183      |
|     April      |       99       |
|      May       |       127      |
|     June       |       202      |
+---------------------------------+
and so on...

Here’s the error message I recieve from the methods I’ve tried:

Error Code: 1055. Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column ‘UsedCarDealer.Sale.SaleDate’ which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Thanks!

Advertisement

Answer

I would suggest:

SELECT MONTHNAME(SaleDate) as "Month", Count(*) as "TotalSales"
FROM Sale
GROUP BY MONTH(SaleDate), MONTHNAME(SaleDate)
ORDER BY MONTH(SaleDate);

This will also return the values in chronological order. Note: When using months, it usually makes sense to include the year as a filter or in the GROUP BY. Perhaps a better version of the query is:

SELECT YEAR(SaleDate) as Year, MONTHNAME(SaleDate) as "Month", Count(*) as "TotalSales"
FROM Sale
GROUP BY YEAR(SaleDate), MONTH(SaleDate)
ORDER BY MIN(SaleDate);
8 People found this is helpful
Advertisement