Trying to write a query to get the total number of sales per month.
So I can currently write this query to return the month and year:
SELECT
DISTINCT(MONTHNAME(STR_TO_DATE(`date`, '%m/%d/%Y'))) AS 'Month'
,YEAR(STR_TO_DATE(`date`, '%m/%d/%Y')) AS 'Year'
,`total`
FROM `supermarket_sales`
And I can return the below:
So what I want to do now is get the total for each month.
Using an answer found here: Total sales per month
And this is my attempt to mimic the accepted answer on the link above:
SELECT
DISTINCT(MONTHNAME(STR_TO_DATE(`date`, '%m/%d/%Y'))) AS 'Month',
YEAR(STR_TO_DATE(`date`, '%m/%d/%Y')) AS 'Year',
SUM(`total`) AS 'TotalSales'
FROM `supermarket_sales`
GROUP BY YEAR(STR_TO_DATE(`date`, '%m/%d/%Y')), MONTH(STR_TO_DATE(`date`, '%m/%d/%Y'))
ORDER BY YEAR(STR_TO_DATE(`date`, '%m/%d/%Y')), MONTH(STR_TO_DATE(`date`, '%m/%d/%Y'))
But I am getting the below error:
How can I make this work?
2
Answers
Once you use aliases for column in SELECT statement you can refer to same later in the query.
i have tried to create simple table with default date format. It is working fine for me.
creating table:
inserting values:
selecting records as you showed in first query.
output of query1
Adding group by and order by:
output of query2
Distinct and Group By in the same sql doesn’t make sense. Since you want the Sum() aggregation by year and month – use Group By and lose Distinct…
You should adjust your code like here:
See the fiddle here.