I am an SQL beginner and ran into the following problem. Consider a table with data on countries, cities within that country and their population:
CREATE TABLE cities (
country VARCHAR(20),
city VARCHAR(20),
population INT
);
INSERT INTO cities VALUES
('Italy', 'Milano', 1000000),
('Italy', 'Rome', 2000000),
('Italy', 'Bologna', 800000),
('Poland', 'Warszawa', 1000000),
('Poland', 'Wroclaw', 700000);
I would like to write a query which returns the country name, alongside the population of its biggest city and the city name itself. The first two fields are straightforward using GROUP BY
. However, I don't know how to include the name of the biggest city. I tried:
SELECT
country, MAX(population), city
FROM
cities
WHERE
population = (SELECT
MAX(population)
FROM
cities
)
GROUP BY country, city;
but this selects only one record (the one about Rome). I'd like the query to return one record per country group, i.e. in this case Rome and Warszawa. The WHERE
condition cannot be:
population = (SELECT
MAX(population)
FROM
cities
GROUP BY country)
because then the subquery returns two rows, leading to Error 1242 in the main query.