简体   繁体   English

在列中查找N个最大元素

[英]Finding N Largest elements in a column

I have a city table comprising of fields such as ID , Name , CountryCode and Population . 我有一个城市表,包括IDNameCountryCodePopulation等字段。 I want to find the top N(say N = 5) cities with the largest Population . 我想找到Population最多的前N个(比如N = 5个)城市。

A very naive way would be to find the city with the largest population using the MAX() group function, and finding the rest via a variant of the method mentioned here. 一种非常天真的方式是使用MAX()组函数找到人口最多的城市,并通过此处提到的方法的变体找到其余的。

What is the simplest SQL Query to find the second largest value? 查找第二大值的最简单的SQL查询是什么?

Does anyone know of a better method to achieve the goal? 有谁知道一个更好的方法来实现目标?

If you just want the top N cities, using order by and limit would be a much simpler approach: 如果你只想要前N个城市,使用order bylimit将是一个更简单的方法:

SELECT   *
FROM     city
ORDER BY population DESC
LIMIT    5 -- or any other N
SELECT *
FROM cities AS c1
WHERE
(SELECT COUNT(*)
 FROM cities AS c2
 WHERE c2.population > c1.population)<5;

This query may return more than five rows if there are several cities with the same population. 如果有多个城市具有相同的人口,则此查询可能返回五行以上。 You didn't specify what result you expect for "top 5" when there are tied values. 当存在绑定值时,您未指定“前5”的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM