The question is taken from problem 25 of SQL Practice Problems Book... [Problem 25][1] [1]: https://i.stack.imgur.com/fmJjs.jpg
- High freight charges
Some of the countries we ship to have very high freight charges. We'd like to investigate some more shipping options for our customers, to be able to offer them lower freight charges. Return the three ship countries with the highest average freight overall, in descending order by average freight.
My first intuition was to run the following query:
SELECT shipcountry, freight
from orders
GROUP BY shipcountry
ORDER BY freight DESC
LIMIT 3;
which is apparently not the correct way to do it. The query below uses avg aggregation function, and is the correct way to query. I wanted to know why we need to run AVG function when we have the GROUP BY?
SELECT shipcountry, avg(freight) as mean_freight
FROM orders
GROUP BY shipcountry
ORDER BY mean_freight DESC
LIMIT 3;