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

用SQL查询方式显示GROUP BY中的TOP
怎样用一个SQL语句来显示
分组后每个组的前几位
比如把一个学校所有学生的成绩按班级分组,再显示每个班级前五名的信息。
班级     学生   成绩
一班     李X       100
一班     王X       99
一班     刘X       98
一班     赵X       97
一班     孙X       96
二班     李W       100
二班     王W       99
二班     刘W       98
二班     赵W       97
二班     孙W       96
......

------解决方案--------------------
declare @t table (class varchar(20),name varchar(10),grade int)
insert @t select '一班 ', '李X ',100
union all select '一班 ', '王X ',99
union all select '一班 ', '刘X ',98
union all select '一班 ', '赵X ',97
union all select '一班 ', '孙X ',96
union all select '一班 ', '孙X ',78
union all select '二班 ', '李W ',100
union all select '二班 ', '王W ',99
union all select '二班 ', '刘W ',98
union all select '二班 ', '赵W ',97
union all select '二班 ', '孙W ',96
union all select '二班 ', '孙X ',88

select * from @t a where
(select count(1) from @t where class=a.class and grade> a.grade) <5
order by class,grade desc
--结果
class name grade
-------------------- ---------- -----------
二班 李W 100
二班 王W 99
二班 刘W 98
二班 赵W 97
二班 孙W 96
一班 李X 100
一班 王X 99
一班 刘X 98
一班 赵X 97
一班 孙X 96

(所影响的行数为 10 行)