有这样一个表
学号 班级 成绩
-------------------------
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 行受影响)
------解决方案--------------------
拍砖啦 呵呵 有些不严谨
若
有这样一个表
学号 班级 成绩
-------------------------
1 1 70
2 1 71
3 1 72
4 2 73
5 2 72
6 2 75
这样的数据就会出错
还是1楼的号点
来点笨方法
select * from test where 学号 in(select 学号 from test where cast(班级 as nvarchar(100))+cast(成绩 as nvarchar(100)) in(select cast(班级 as nvarchar(100))+cast(max(成绩)as nvarchar(100)) as flag from test group by 班级) )
------解决方案--------------------
create table cj(学号 int, 班级 int, 成绩 int)
insert into cj
select 1, 1, 70 union all