日期:2014-05-18  浏览次数:20384 次

实现排名
一个数据库记录学生的总成绩 
查找其排名: 
SELECT COUNT(*) AS number FROM mark WHERE score>我的成绩 
但如果想知不同时期考试的排名呢? 
如今学期同上一学期的排名
能用一条SQL实现吗? 
数据库: 
id , date,score 



------解决方案--------------------
SQL code

create table T(
学号 int,
时间 nvarchar(10),
分数 int
)

insert T select 1, '每一学期', 80 
union all select 1, '每二学期', 90 
union all select 2, '每一学期', 85 
union all select 2, '每二学期', 99 
union all select 3, '每一学期', 70 
union all select 3, '每二学期', 86

select 排名=(select count(distinct 分数) from T where 时间=tmp.时间 and 分数>=tmp.分数),* from T as tmp
order by 时间,1

------解决方案--------------------
SQL code
--RESULT.分数相同的并列名次
date       number      id          score
---------- ----------- ----------- -----------
2007-1-1   1           3           100
2007-1-1   2           2           90
2007-1-1   2           4           90
2007-1-1   4           1           80
2007-5-1   1           2           80
2007-5-1   1           3           80
2007-5-1   3           1           70
2007-5-1   4           4           60
2007-7-1   1           1           90
2007-7-1   2           2           80
2007-7-1   3           4           70
2007-7-1   4           3           50

------解决方案--------------------
create table tb(学号 int,时间 varchar(20),分数 int)
insert into tb values(1, '每一学期', 80) 
insert into tb values(1, '每二学期', 90) 
insert into tb values(2, '每一学期', 85) 
insert into tb values(2, '每二学期', 99) 
insert into tb values(3, '每一学期', 70) 
insert into tb values(3, '每二学期', 86) 
select * , 排名=(select count(1) from tb where 时间=a.时间 and 分数 > a.分数 ) + 1 from tb a
drop table tb

/*
学号 时间 分数 排名
----------- -------------------- ----------- ----------- 
1 每一学期 80 2
1 每二学期 90 2
2 每一学期 85 1
2 每二学期 99 1
3 每一学期 70 3
3 每二学期 86 3

(所影响的行数为 6 行)
*/