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

用游标如何实现
请教下大家:
   如果有一张成绩表,成绩表中包含了五个科目的成绩,相当于一个学生有五条记录在里面,那么如果要得到每个成绩的前三名。用游标如何实现呢?

------解决方案--------------------
用什么游标?

select top 3 * from table where 科目 = 要查询的科目 order by 成绩
------解决方案--------------------
select top 3 * from t_table 
where 
classname = 'math'
order by score_math desc
------解决方案--------------------
id      学号     科目    成绩
id stu_id subject score
1 1 a 90
2 1 b 80
3 1 c 87
4 2 a 78
5 2 b 98
6 2 c 88
7 3 a 60
8 3 b 67
9 3 c 76
10 4 a 99
11 4 b 98
12 4 c 87
13 5 a 67
14 5 b 76
15 5 c 78

select * from
(
select 
stu_id ,
subject, 
score, 
rank() over (partition by subject order by score desc) as row_num 
from tscore
) t
where t.row_num < 4


stu_id subject score row_num
4 a 99 1
1 a 90 2
2 a 78 3
4 b 98 1
2 b 98 1
1 b 80 3
2 c 88 1
1 c 87 2
4 c 87 2