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

这个groupby怎么写
有这样一个表
学号   班级   成绩
-------------------------
1     1      70
2     1      71
3     1      72
4     2      73
5     2      74
6     2      75

想得到每个班级成绩最高的那个人的学号,当然成绩有可能相等

学号   班级   成绩
-------------------------
3     1     72
6     2     75

select max(成绩)
from 表
group by 班级 

可是这样得不到学号呀

比如我想给每个班成绩最好的人的成绩再加上他的课外成绩,这就需要那学号当主键

------解决方案--------------------
create table #tbb(xuhao int,banji varchar(100),chengji int)
insert into #tbb
 select 1,'1',70
union all select 2,'1',71
union all select 3,'1',72
union all select 4,'2',73
union all select 5,'2',74
union all select 6,'2',75

;with cte as
(
select rank() over ( partition by banji  order by chengji desc)ID,xuhao,banji,chengji from #tbb
)
select xuhao,banji,chengji from cte where ID=1

------解决方案--------------------
create table test(学号 int,班级 int,成绩 tinyint)
go
insert into test
 select 1,'1',70
union all select 2,'1',71
union all select 3,'1',72
union all select 4,'2',73
union all select 5,'2',74
union all select 6,'2',75
go
select * from test

 select 学号,班级,成绩 from test --如果只需学号,则班级,成绩可不写
 where 成绩 in 
(select max(成绩) from test group by 班级)

学号          班级          成绩
----------- ----------- ----
3           1           72
6           2           75

(2 行受影响)

------解决方案--------------------
引用:
create table test(学号 int,班级 int,成绩 tinyint)
go
insert into test
 select 1,'1',70
union all select 2,'1',71
union all select 3,'1',72
union all select 4,'2',73
union all select 5,'2',74
union all select 6,'2',75
go
select *&nbs