选择最大列的值不会提供所需的结果

时间:2015-05-18 12:29:03

标签: mysql sql

有一个名为cities的表,看起来像这样:

id | city | population | year

我只需要:

对于每个城市,选择最大人口数量和最大人口数量。首选

是没有嵌套查询的解决方案

所以我尝试了这个:

SELECT `city`, MAX(`year`), MAX(`population`) FROM `cities` GROUP BY `city`

但它给出了错误的结果。我做错了什么?

1 个答案:

答案 0 :(得分:2)

首先,你必须采取超过你需要的最大人口数量。试试这个:

SELECT C.city, max(C2.year), C.MAX_population
FROM 
(SELECT city, MAX(population) AS MAX_population FROM cities GROUP BY city) C
JOIN cities C2 on C2.city = C.city and C2.population = C.MAX_population
GROUP BY C.city, C.MAX_population