日期:2014-05-17  浏览次数:20683 次

取每个班前5名成绩的sql怎么写
比如有个学生总表
class id  name  score
分别是班级,学号,姓名,学分

这里面包含了很多个班级的很多学生。
如果一条语句求出每个班级前5名的同学。

------解决方案--------------------

select class,id,name,score,rn
from
(select class,id,name,score,
       row_number() over(partition by class order by score desc) 'rn'
 from 学生总表) t where t.rn<=5

------解决方案--------------------


--尝试下排名函数,呵呵

create table Table_1
(
class varchar(10), id varchar(10),  name varchar(10), score decimal(8,2)
)

insert into Table_1 values ('1','N1','A',87.89)
insert into Table_1 values ('1','N2','B',77.89)
insert into Table_1 values ('1','N3','C',88.67)
insert into Table_1 values ('1','N4','D',66.89)
insert into Table_1 values ('1','N5','E',88.65)
insert into Table_1 values ('1','N6','E',99.65)
insert into Table_1 values ('2','NA','Z',87.89)
insert into Table_1 values ('2','NB','X',77.89)
insert into Table_1 values ('2','NC','V',88.67)
insert into Table_1 values ('2','ND','Y',66.89)
insert into Table_1 values ('2','NE','U',88.65)
insert into Table_1 values ('2','NF','T',99.65)


SELECT * FROM Table_1

select * from
(SELECT  RANK() OVER(PARTITION BY  CLASS ORDER BY score desc) AS 排名,* FROM Table_1 )t
where t.排名<=5