我试图在查询中获得每个国家/地区中任何城市的最大人口。我需要加入城市和国家/地区表格,因为它们位于两个表格中,并通过国家/地区代码加入。
我有以下查询:
SELECT country.name AS country,
city.name AS city,
Max(city.population) AS max_pop
FROM country
INNER JOIN city
ON( country.country_code = city.country_code )
GROUP BY country.name,
city.name
ORDER BY country.name ASC;
我的思维过程是从联接表中获取我的国家/地区名称,城市名称和最大值。我假设并经过测试,max只会给我一个结果,但在这种情况下它会给我几个!我的小组中有城市和国家/地区名称,以便让它运行。
思想?
答案 0 :(得分:2)
SELECT co.name AS country,
ct.name AS city,
t.pop AS max_pop
FROM country AS co
INNER JOIN (
SELECT country_code, Max(population) AS pop FROM city GROUP BY country_code
) t ON co.country_code = t.country_code
INNER JOIN city AS ct ON ct.population = t.pop AND co.country_code = ct.country_code
ORDER BY country.name ASC;
答案 1 :(得分:2)
DISTINCT ON
(SQL标准的PostgreSQL扩展)更多更短更快:
SELECT DISTINCT ON (1)
co.name AS country
,ci.name AS city
,ci.population AS max_pop
-- add more columns as you please
FROM country co
JOIN city ci USING (country_code)
ORDER BY 1, 3 DESC, 2;
如果两个城市在一个国家/地区拥有同等数量的人口,我会在这种情况下首先按字母顺序选择。这就是我将位置参数2 (对于ci.name
)添加到ORDER BY
子句的原因。
我还简化了表别名和USING
equi-join。
关于DISTINCT ON
: