轉載:https://www.cnblogs.com/niniya/p/9046449.html
一、排名
/*普通排名:從1開始,順序往下排*/ SELECT cs.*,@r :=@r + 1 AS rank FROM cs,(SELECT @r := 0) r ORDER BY score;

/*並列排名:相同的值是相同的排名*/ SELECT cs.* , CASE WHEN @p=score THEN @r WHEN @p:=score THEN @r:=@r+1 END rank FROM cs,(SELECT @r:=0,@p:=NULL)r ORDER BY score;

/*並列排名:相同的值名次相同,與上例中的並列排名不同*/ SELECT city,score,rank FROM ( SELECT cs.*, @c:=IF(@p=score,@c,@r) AS rank, @p:=score, @r:=@r+1 FROM cs ,(SELECT @p:=NULL,@r:=1,@c:=0)r ORDER BY score )c

二、分組后組內排名
/*分組普通排名:順序排名*/ SELECT city,score,rank FROM ( SELECT cs.*,IF(@p=city,@r:=@r+1,@r:=1) AS rank, @p:=city FROM cs,(SELECT @p:=NULL,@r:=0)r ORDER BY city,score )s;

/* 分組后並列排名:組內相同數值排名相同*/
SELECT city,score,rank
FROM
(
SELECT *,
IF(@p=city,
CASE
WHEN @s=score THEN @r
WHEN @s:=score THEN @r:=@r+1
END,
@r:=1 ) AS rank,
@p:=city,
@s:=score
FROM cs,(SELECT @p:=NULL,@s:=NULL,@r:=0)r
ORDER BY city,score
)s;

三、分組后取各組的前兩名
/*取每組分數高的前兩個,法一*/
SELECT city,score,rank
FROM
(
SELECT *,
IF(@p=city,
CASE
WHEN @s=score THEN @r
WHEN @s:=score THEN @r:=@r+1
END,
@r:=1 ) AS rank,
@p:=city,
@s:=score
FROM cs,(SELECT @p:=NULL,@s:=NULL,@r:=0)r
ORDER BY city,score DESC
)s
WHERE rank <3;

/*分組后取前兩個,法二*/
SELECT * FROM cs c
WHERE (
SELECT count(*) FROM cs
WHERE city=c.city AND score>c.score )<2
ORDER BY city,score DESC

參考:
https://www.jianshu.com/p/bb1b72a1623e
http://blog.sina.com.cn/s/blog_4c197d420101e408.html

