假设我们有一个像这样的城市的州(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来执行此操作?
更新:
让我说清楚:结果应该包含每个州人口最多的一个城市。在上面的示例中,“圣地亚哥”的人口数量少于“洛杉矶”,因此不会显示在结果中。
答案 0 :(得分: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 ;
答案 1 :(得分:1)
select *
from pop
where (state, population) in
(select state, max(population)
from pop
group by state);
答案 2 :(得分:0)
就这样做:
SELECT state, city, MAX(population) AS LargestPeople FROM yourtable GROUP BY state DESC