34,591
社区成员
发帖
与我相关
我的任务
分享
select
名字 = a1.name
,班级 = a2.name
from
student as a1
inner join class as a2 on a2.id = a1.c_Id
where a1.score = (select 最高分 = max(score) from student)
use tempdb;
if object_id('#student') is not null
drop table #student
select '001' as id ,1 as c_id,'张三' as name,'男' as sex,90 as score
into #student
union all
select '002' as id ,1 as c_id,'李四' as name,'女' as sex,80 as score union all
select '003' as id ,1 as c_id,'王五' as name,'男' as sex,65 as score union all
select '004' as id ,2 as c_id,'小刘' as name,'男' as sex,60 as score union all
select '005' as id ,2 as c_id,'赵六' as name,'女' as sex,75 as score union all
select '006' as id ,2 as c_id,'李五' as name,'女' as sex,90 as score
if object_id('#class') is not null
drop table #class
select 1 as id,'一班' as name
into #class
union all
select 2 as id,'二班' as name
-- 如果是想获取 score表最大分数的学生信息.....SQL如下
select t2.name as c_name,t1.name,t1.sex,t1.score
from #student t1
left join #class t2
on t1.c_id=t2.id
where score in (
select max(score) from #student
)
order by t1.id
--
-- 如果是想获取 score表不同性别成绩最高的分数以及这个学生的信息...SQL如下
select t2.name as c_name,t1.name,t1.sex,t1.score
from #student t1
left join #class t2
on t1.c_id=t2.id
join (select sex,max(score) as score from #student group by sex) t3 --如果你的需求真的是科目字段,这里group by 科目字段即可,select 中也是科目字段,max(score)
on t1.sex=t3.sex and t1.score=t3.score
order by t1.id
结果如下图