簡體   English   中英

如何獲取每組mysql查詢中的第n個最高條目

[英]How to get the nth highest entry in each group of mysql query

我是 MySQL 的初學者,過去幾天我偶然發現了這一點。

假設我有一個國家/地區表,如下所示:

code    name            continent       Population
ABW Aruba               North America   103000
AFG Afghanistan         Asia            22720000
AGO Angola              Africa          12878000
AIA Anguilla            North America   8000
ALB Albania             Europe          3401200
AND Andorra             Europe          78000
ARG Argentina           South America   37032000

該表包含每個國家的大陸和人口信息。

我如何找到每個大陸中人口第 n 位最高的國家?

對於特定場景,我如何找到每個大陸中人口第三高的國家?

我檢查了很多 SO 問題,包括這個鏈接 但是找不到這個問題的答案。 任何幫助將不勝感激!

      with result as 
      (
        select code,name,continent,population,dense_rank() over( order by population ) as rnk 
        from dbo.country
       )
      select population,continent from result where rnk=3 group by continent,population  ;

如果你想要第二高的人口,那么在 where 子句中輸入 rnk 作為 2 等等..

假設沒有國家擁有相同的人口,那么一種方法是計算擁有相同或更高人口的國家的數量,並查看計數何時為 3:

select c.*
from country c
where (select count(*)
       from country c2
       where c2.continent = c.continent and c2.population >= c.population
      ) = 3;

一種選擇是使用變量。

select code,name,continent,population 
from (
select c.*, 
@prevPopulation:=@curPopulation,
@curPopulation:=population,
@prevContinent:=@curContinent,
@curContinent:=continent,
case when @curContinent = @prevContinent and @prevPopulation <> @curPopulation then @rn:=@rn+1
     when @curContinent = @prevContinent and @prevPopulation = @curPopulation then @rn:=@rn
else @rn:=1 end as rank
from country c,
(select @rn := 0, @curContinent := '',@prevContinent := '', @curPopulation:=0,@prevPopulation:=0) r
order by continent,population desc
) x
where rank = 3 --replace it with the nth highest value needed

此查詢使用 4 個變量

1) @curContinent 最初設置為空字符串。 此后, select分配當前行的大陸。

2) @prevContinent 最初設置為空字符串。 此后, select將其設置為 @curContinent 值(最初是一個空字符串)。

3) @curPopulation 最初設置為 0。此后select分配當前行的人口。

4) @prevPopulation 最初設置為 0。此后select將其設置為 @curPopulation(第一次為 0,依此類推)。

order by子句在這里很重要,可以根據大陸和人口指定當前行和前一行。 這也可以處理關系,因為它會將相同的等級分配給具有相同人口的大陸內的所有國家。

最初運行內部查詢以查看變量是如何設置的,這將為您澄清事情。

Sample Demo

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM