1

我试图在查询中获得每个国家/地区任何城市中最大的人口。我需要加入城市和国家表,因为它们位于两个表上,并通过国家代码加入它们。

我有以下查询:

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; 

我的想法是从连接表中获取我的国家名称、城市名称和最大值。我假设并测试过,最大值只会给我一个结果,但是在这种情况下它会给我几个!为了让它运行,我在我的组中同时拥有城市和国家名称。

想法?

4

2 回答 2

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; 
于 2013-03-12T02:21:05.727 回答
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 (for ci.name) 。ORDER BY

我还使用表别名和USINGequi-join 进行了简化。

关于DISTINCT ON

于 2013-03-12T03:37:21.873 回答