在sql中根據成績顯示學生排名

一、準備函數

 1 create table newtable
 2 (
 3   name VARCHAR(100),
 4   yuwen INT(10),
 5   shuxue INT(10)
 6 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 7 
 8 
 9 INSERT INTO newtable (name, yuwen, shuxue) VALUES ('張三', 80, 67);
10 INSERT INTO newtable (name, yuwen, shuxue) VALUES ('李四', 98, 65);
11 INSERT INTO newtable (name, yuwen, shuxue) VALUES ('王五', 59, 98);
12 INSERT INTO newtable (name, yuwen, shuxue) VALUES ('趙六', 76, 87);
13 INSERT INTO newtable (name, yuwen, shuxue) VALUES ('田七', 69, 85);

二、實現url

 1 select yuwentable.name studentname,yuwentable.yuwen yuwenscore ,cast(yuwentable.rank as SIGNED) yuwenrank,shuxuetable.shuxue shuxuescore,cast(shuxuetable.rank as SIGNED) shuxuescore 
 2 from 
 3   (  
 4     select (@yuwenrank:=@yuwenrank+1) as rank,name,yuwen 
 5     from newtable a,(select (@yuwenrank:=0)) b order by a.yuwen desc
 6   ) yuwentable ,
 7   (
 8     select (@shuxuerank:=@shuxuerank+1) as rank,name,shuxue 
 9     from newtable a,(select (@shuxuerank:=0)) b order by a.shuxue desc
10   ) shuxuetable
11   where yuwentable.name = shuxuetable.name order by yuwentable.name

說明:在DbVisualizer中,代碼執行後,RANK這列含有小數點,因此這裏經過case函數將其轉換整數spa

三、結果code

studentname yuwenscore yuwenrank shuxuescore shuxuescore 
----------- ---------- --------- ----------- ----------- 
張三          80         2         67          4           
李四          98         1         65          5           
王五          59         5         98          1           
田七          69         4         85          3           
趙六          76         3         87          2   

 

若是,您認爲閱讀這篇博客讓您有些收穫,不妨點擊一下右下角的【推薦】。
若是,您但願更容易地發現個人新博客,不妨點擊一下左下角的【關注我】。
若是,您對個人博客所講述的內容有興趣,請繼續關注個人後續博客,我是【劉超★ljc】。blog

本文版權歸做者,禁止轉載,不然保留追究法律責任的權利。get

相關文章
相關標籤/搜索