前文 :這只是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 後面接的是聚合函數 ;
----------------------------------------------------------------------學習一下吧 ;