I have a table containing the monthly sales of a car-salesman who sells 3 different brands. I want to create a query which returns a table of the year, month and best selling car brand with the amount sold for that month.
A portion of the table is bellow:
+-----+--------+-----------+-------------+
|NYEAR| NMONTH | CAR_BRAND | AMOUNT_SOLD |
+-----+--------+-----------+-------------+
|2018 12 HONDA 15 |
|2018 12 TOYOTA 12 |
|2018 12 FORD 22 |
|2019 1 HONDA 14 |
|2019 1 TOYOTA 13 |
|2019 1 FORD 34 |
|2019 2 TOYOTA 10 |
|2019 2 FORD 19 |
|2019 2 HONDA 13 |
|2019 3 FORD 14 |
|2019 3 OYOTA 13 |
|2019 3 HONDA 15 |
|2019 4 HONDA 12 |
|2019 4 TOYOTA 14 |
|2019 4 FORD 11 |
|2019 5 FORD 11 |
|2019 5 HONDA 13 |
|2019 5 TOYOTA 10 |
+-----+--------+-----------+-------------+
I am able to get the answer of the Max AMOUNT_SOLD per month but can't get the stores name. Here's the query I tried.
SELECT NYEAR, NMONTH, MAX(SALES_AMOUNT)
FROM MONTHLY_CAR_SALES
GROUP BY NYEAR, NMONTH;
However when I tried to add CAR_BRAND into the select of the query:
SELECT NYEAR, NMONTH, CAR_BRAND, MAX(SALES_AMOUNT)
FROM MONTHLY_CAR_SALES
GROUP BY NYEAR, NMONTH;
I get:
Error Code: 1055. Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'USED_CAR_SALES.MONTHLY_CAR_SALES.CAR_BRAND' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
When I try to add CAR_BRAND into the grouping clause it returns the exact same table as above, which shows every brand for every month.
The table I'm after is like this:
+-----+--------+-----------+-------------+
|NYEAR| NMONTH | CAR_BRAND | AMOUNT_SOLD |
+-----+--------+-----------+-------------+
|2018 12 FORD 22 |
|2019 1 FORD 34 |
|2019 2 FORD 19 |
|2019 3 HONDA 15 |
|2019 4 TOYOTA 14 |
|2019 5 HONDA 13 |
+-----+--------+-----------+-------------+