码迷,mamicode.com
首页 > 数据库 > 详细

在sql中根据成绩显示学生排名

时间:2017-08-21 13:34:41      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:name   ref   block   mic   char   default   eof   实现   desc   

1、准备

 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);

2、实现

 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函数将其转换整数

3、结果

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】。

本文版权归作者,禁止转载,否则保留追究法律责任的权利。

在sql中根据成绩显示学生排名

标签:name   ref   block   mic   char   default   eof   实现   desc   

原文地址:http://www.cnblogs.com/codeOfLife/p/7403765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!