1

假设我们有一个像这样的城市的州 (varchar)、城市 (varchar) 和人口 (int) 表,

New York, New York, 8175133
Los Angeles, California, 3792621
Chicago, Illinois, 2695598
San Diego, California, 1307402

我想选择每个州人口最多的城市。结果是,

New York, New York, 8175133
Los Angeles, California, 3792621
Chicago, Illinois, 2695598

如何编写 SQL 来做到这一点?

更新:

让我说清楚:结果应该包含每个人口最多的州一个城市。在上面的示例中,“圣地亚哥”的人口少于“洛杉矶”,因此它不会出现在结果中。

4

3 回答 3

8

在极少数情况下,两个或多个城市的人口相同,两者都将显示:

SELECT 
    t.*
FROM 
    tableX  t
  JOIN
    ( SELECT State
           , MAX(Population) AS Population 
      FROM tableX
      GROUP BY State
    ) maxp  
        ON  maxp.State = t.State
        AND maxp.Population = t.Population 

如果您的 DBMS 具有分析(窗口)功能,您也可以使用它(与前面显示的关系):

SELECT 
    City
  , State
  , Population
FROM 
    ( SELECT City
           , State
           , Population
           , RANK() OVER ( PARTITION BY State 
                           ORDER BY Population DESC )
               AS RankN
      FROM tableX
    ) maxp  
WHERE RankN = 1 ;

或者这个(关系已解决,每个状态只返回一行):

SELECT 
    City
  , State
  , Population
FROM 
    ( SELECT City
           , State
           , Population
           , ROW_NUMBER() OVER ( PARTITION BY State 
                                 ORDER BY Population DESC 
                                        , City ASC )
               AS RowN
      FROM tableX
    ) maxp  
WHERE RowN = 1 ;

SQL-Fiddle中测试

于 2012-05-14T21:14:45.153 回答
1
select *
from pop 
where (state, population) in 
   (select state, max(population) 
    from pop 
    group by state);
于 2012-05-14T22:57:03.067 回答
0

去做就对了:

SELECT state, city, MAX(population) AS LargestPeople FROM yourtable GROUP BY state DESC
于 2012-05-14T21:10:45.310 回答