I have a table, table 1. In this table is name, city, price. The names are all unique, the cities can be reused. I want to make a query that gives me the highest price of each city, and the name associated with that row. To get the highest price of each city I just do:
SELECT MAX(price), city FROM table1 GROUP BY city
But I want the name as well. If I try
SELECT MAX(price), city, name FROM table1 GROUP BY city
Then I just get a query error about how name isn’t included in the group by. If I add name to the group by, then it doesn’t do what I want. I can think of how I could do this using two queries, but I bet there’s a way to do it in just one. What am I missing?
I’ve found a few similar questions on stackoverflow, but they all seem to be doing something more complicated than I’m attempting to. I’ve only ever used simple SQL queries, so I’m educating myself on some of the more advanced features.
Note that you didn’t specify what should happen if two products in a city are both the most expensive and equal in their price. This query here returns any of the two (but only one), you could also handle this differently.