Imagine you have the following table named city
:
market | product | cost |
---|---|---|
A | 1 | 54 |
A | 2 | 62 |
A | 3 | 38 |
B | 1 | 12 |
B | 2 | 12 |
B | 3 | 5 |
I need the most expensive product for each market, i.e.:
market | product | cost |
---|---|---|
A | 2 | 62 |
B | 1 | 12 |
B | 2 | 12 |
I know this SQL query doesn’t work:
SELECT *, MAX(cost)
FROM city
GROUP BY market
The point isn’t finding a solution (that’s pretty easy I think).
My question: is there a specific reason why the SQL language doesn’t evolve to allow the query above to find the result?
2
Answers
if you are getting error ‘city.idt’ is invalid…
it is because when you are using MAX or SUM or other similar functions in sql
you should specify other coloumns that you want in group by
for example
so there we want market so we should specify it in group by
the result will be
cost market
64 A
12 B
if you want to get other columns without specifying them in the group by:
SELECT
*
FROM
city
WHERE
cost IN
(
SELECT
DISTINCT
MAX(cost)
FROM
city
GROUP BY
market
)
ORDER BY
market ASC
You can use a subselect or a CTE to get the results. First get the maximum price in the market, and then list the products
Here you have the query with the subselect:
And using CTE:
In both cases you get the desired result: