SQL问题:各班前三名的学号

来源:百度知道 编辑:UC知道 时间:2024/09/28 13:09:22
表T,有A,B,C三列,A是班级号,B是学号,C是成绩。
要求各班前三名的学号。请问该如何写SQL?

不小得楼上怎么会写得那么多哈!,,,,

select top 3 B
from T
group by A
order by C desc;

好像这样就行了哈!

我们经常会有这样的需求,即按照地区来分别取出每个地区排名前3的那些记录。本文总结了几种方法,希望大家补充。

首先,创建测试用的表和数据,如下:

create table test
(
areaid int,
score int
)
insert into test select 0,10
union all select 0,20
union all select 0,30
union all select 0,40
union all select 0,50
union all select 1,10
union all select 1,20
union all select 1,30
union all select 1,40
union all select 1,50
union all select 2,10
union all select 2,20
union all select 2,30
union all select 2,40
union all select 2,50
go

第一种方法适用于sql2000和2005,其代码如下:

select * from test a
where checksum(*) in (select top 3 checksum(*) from test b where a.areaid=b.areaid order by score desc)

第二种方法是利用sql2005的函数ROW_NUMBER,其代码如下:

WITH test1 AS
(
SELECT *,
ROW_NUMB