从2个表中获取数据并编写查询

时间:2014-10-13 00:02:28

标签: sql postgresql greatest-n-per-group

我在php中遇到问题。我似乎无法获得我想要的输出。 我想写的查询是

  

对于每个国家/地区,列出其所有城市中最大的人口和   那个城市的名字。按照城市人口的递减顺序排列结果。

这是我尝试过的代码,以及我尝试过的表:

SELECT MAX(population) as population, name
FROM what.city
ORDER BY population DESC

以下是我正在使用的表格:

               Table "what.country"
     Column      |         Type          |               Modifiers              
-----------------+-----------------------+--------------------------------------
 country_code    | character(3)          | not null default ''::bpchar
 name            | character varying(52) | not null default ''::character varying
 continent       | continent             | not null
 region          | character varying(26) | not null default ''::character varying
 surface_area    | real                  | not null default 0::real
 indep_year      | smallint              | 
 population      | integer               | not null default 0
 life_expectancy | real                  | 
 gnp             | real                  | 
 gnp_old         | real                  | 
 local_name      | character varying(45) | not null default ''::character varying
 government_form | character varying(45) | not null default ''::character varying

               Table "what.city"
    Column    |         Type          |                     Modifiers                    
--------------+-----------------------+-----------------------------------------
 id           | integer               | not null default nextval('city_id_seq'::regclass)
 name         | character varying(35) | not null default ''::character varying
 country_code | character(3)          | not null default ''::bpchar
 district     | character varying(20) | not null default ''::character varying
 population   | integer               | not null default 0

1 个答案:

答案 0 :(得分:1)

目前接受的答案不正确。在Postgres实现这一目标的一种简单快捷的方法是使用DISTINCT ON

SELECT co.name AS country_name, ci.city_name, population
FROM  (
   SELECT DISTINCT ON (country_code)
          country_code, name AS city_name, population
   FROM   what.city
   ORDER  BY country_code, population DESC
   ) ci
JOIN  what.coutry co USING (country_code);

详细说明: