一个选项来做到这一点使用变量。
select code,name,continent,population
from (
select c.*,
@prevPopulation:[email protected],
@curPopulation:=population,
@prevContinent:[email protected],
@curContinent:=continent,
case when @curContinent = @prevContinent and @prevPopulation <> @curPopulation then @rn:[email protected]+1
when @curContinent = @prevContinent and @prevPopulation = @curPopulation then @rn:[email protected]
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
诚然,这是做一个漂亮的调皮事,但假设没有在一个大陆的2个国家有着相同的,明显估计的情况,似乎是这样的混乱。先生,所有应有的尊重。已经有人说过......我没有想到更好的解决方案。 –
一种替代方法是使用变量。或者是一个正确支持'row_number()','rank()'等的数据库。 –