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

跪求 group by 和 top 还有 order by 结合的例子
从一个表(tta)中取每个班的总分(points)前三名,表结构如下
表名:tta
列1:学号-sid
列2:姓名-sname
列3:班级-sclass
列4:总分-ptotal
现在要取出每个班总分前3名的学生,不知道如何写MS   sql   server   语句?

------解决方案--------------------
--建立测试环境
create table #tb(student_id int,course_id varchar(10),score int)
insert #tb(student_id,course_id,score)
select '1 ', '001 ', '50 ' union all
select '1 ', '002 ', '34 ' union all
select '2 ', '001 ', '49 ' union all
select '2 ', '002 ', '54 ' union all
select '3 ', '001 ', '50 ' union all
select '3 ', '002 ', '49 ' union all
select '4 ', '001 ', '40 ' union all
select '4 ', '002 ', '44 '
go
--查询每科前三名的学生,只取三名
select _t.course_id,_t.student_id,_t.score
from #tb _t
where student_id in(select top 3 student_id from #tb where course_id = _t.course_id order by score desc,student_id)
order by course_id,score desc,student_id

/*--测试结果
course_id student_id score
---------- ----------- -----------
001 1 50
001 3 50
001 2 49
002 2 54
002 3 49
002 4 44

(6 行受影响)
*/

--查询每科前三名的学生,当第三名并列时会多于三名
select _a.course_id,_a.student_id,_a.score
,count(distinct _b.score)+1 as ordinal1--名次1,并列对后面的名次没有影响
,count(_b.score)+1 as ordinal2--名次2,并列会使名次不连续
from #tb _a
left join #tb _b on _a.course_id = _b.course_id and _a.score < _b.score
group by _a.student_id,_a.course_id,_a.score
having count(_b.score)+1 <= 3
order by _a.course_id,_a.score desc,_a.student_id

/*--测试结果
course_id student_id score ordinal1 ordinal2
---------- ----------- ----------- ----------- -----------
001 1 50 1 1
001 3 50 1 1
001 2 49 2 3
002 2 54 1 1
002 3 49 2 2
002 4 44 3 3
警告: 聚合或其他 SET 操作消除了空值。

(6 行受影响)
*/
go
--删除测试环境
drop table #tb
go

------解决方案--------------------
select
t.*
from
tta t
where
t.sid in(select top 3 sid from tta where sclass=t.sclass order by ptotal desc)
order by
t.sclass,t.ptotal desc
------解决方案--------------------
先用游标把班级保存起来,然后循环用每个班级作条件取出每个班前三名放入一个临时表中,最后返回临时表的数据
------解决方案--------------------
select * from tta t
where sid in (select top 3 sid from tta where sclass=t.sclass order by ptotal desc)
order by sclass,ptotal desc
------解决方案--------------------
select * from [Table] a where 学号 in(select top 3 with ties 学号 from [Table] where 班级=a.班级 order by 总分 desc )