时间:2021-12-17 10:04:22 | 栏目:Mysql | 点击:次
从1开始,按照顺序一次往下排(相同的值也是不同的排名)。
set @rank =0; select city , score, @rank := @rank+1 rank from cs order by score desc;
结果如下:
相同的值是相同的排名(但是不留空位)。
set @rank=0,@price=null; select cs.* , case when @price = score then @rank when @price := score then @rank := @rank+1 end rank from cs order by score desc; -- 当查询的score 值 = @price时,输出@rank, -- 当不等时,将score值赋给@price ,并输出@rank := @rank+1 -- 或者 set @rank=0,@price=null; select a.city,a.score,a.rank from (select cs.*, @rank := if(@p=score,@rank,@rank+1) rank, @p := score from cs order by score desc) a;
结果如下:
相同的值是相同的排名(但是留空位)。
set @rank=0,@price=null, @z=1; select a.city,a.score,a.rank from (select cs.*, @rank := if(@p=score,@rank,@z) rank, @p := score,@z :=@z+1 from cs order by score desc) a;
结果如下:
从1开始,按照顺序一次往下排(相同的值也是不同的排名)。
set @rank=0,@c=null; select cs.city,cs.score, @rank := if(@c = city,@rank+1,1) rank, @c := city from cs order by cs.city,cs.score;
结果如下:
组内相同数值排名相同,不占空位。
set @rank=0,@c=null,@s=null; select cs.city,cs.score, @rank := if(@c=city,if(@s=score,@rank,@rank+1),1) rank , @c := city, @s :=score from cs order by cs.city,cs.score;
结果如下:
组内相同数值排名相同,需要占空位。
set @rank=0,@c=null,@s=null; select cs.city,cs.score, @rank := if(@c=city,if(@s=score,@rank,@rank+1),1) rank , @c := city, @s :=score from cs order by cs.city,cs.score;
结果如下:
① 方法一:按照分组排名的三种方式,然后限定排名的值
set @rank=0,@z=0,@c=null,@s=null; select a.city,a.score,a.rank from (select cs.city city,cs.score score, @z := if(@c=city,@z+1,1), @rank := if(@c=city,if(@s=score,@rank,@z),1) rank, @c := city, @s :=score from cs order by cs.city,cs.score desc) a where a.rank<=2;
结果如下:
② 内部查询
SELECT * FROM cs c WHERE ( SELECT count(*) FROM cs WHERE c.city=cs.city AND c.score<cs.score )<2 ORDER BY city,score DESC;
结果如下:
上述代码的执行原理如下图: