前文 :这只是mysql 没有rank() 函数。。。
---------------------------------------------------------------------
Sc表
字段: sid 学生id , subject科目,score 分数
------------------- 普及一下 怎么 给分数加上排名
select * from tab;
##################
id subject score
1 语文 80
2 语文 70
3 语文 75
4 语文 70
5 语文 90
6 语文 60
7 语文 100
########################
select t.*,
(select count(1)+1 from tab where tab.score > t.score) 排名
from tab t;
-------------------- 根据 分数 加上排名
------------------------------------------------------------ 接下来 是 根据科目 给分数加排名
我的做法是 先给 所有的 科目 --分数 加上排名
select s1.*,
(select count(1) from sc s2 where s2.cid = s1.cid and s2.score > s1.score )+1 as 排名
from sc s1 order by s1.cid,排名;
然后 再限制条件 排名 <=3
select s1.*,
(select count(1) from sc s2 where s2.cid = s1.cid and s2.score > s1.score )+1 as 排名
from sc s1 having 排名 <= 3 order by s1.cid,排名;
--------------------- 注意:having 后面接的是聚合函数 ;
----------------------------------------------------------------------学习一下吧 ;
ps: 写法2
SELECT
s1.*
FROM
test s1
WHERE
(
SELECT
count(1)
FROM
test s2
WHERE
s2.subject = s1.subject
AND s2.score > s1.score
) < 3
ORDER BY
s1.subject,
s1.score desc