编写SQL语句查询出每个各科班分数最高的同学的名字,班级名称,课程名称,分数...

本文提供了一种使用SQL语句来查询每个班级和科目中分数最高的学生的解决方案,包括姓名、班级名称、课程名称和分数。对比了两种不同的实现方式,一种使用临时表,另一种则通过联接和聚合函数直接完成查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

这个问题是在csdn上一位朋友写的,但是答案有点复杂,而且查询使用的效率也不是很好,于是自己也写了一个。以下是表结构和数据,

有以下两张表,
Class表
classid classname
1 高三(一)班
2 高三(二)班
3 高三(三)班
Student表
studentid   studentName classid
1    张三            2
2     李四           1
3    王五             1
4    赵六             3
5    钱七             2
6     孙九          3
score表
scoreid course studentid score
1 数学 2 99
2 数学 3 60
3 数学 4 80
4 语文 5 79
5 语文 6 58
6  语文 1 66
7  英语 6 76
8 英语 4 87
9 英语 3 100
10 英语 2 69
编写SQL语句查询出每个各科班分数最高的同学的名字,班级名称,课程名称,分数(问题有点绕口)

朋友的答案:

if exists(select count(*) from sysobjects where type='U' and name='#temp')
   drop table #temp
select p.studentid,studentname,p.classid,classname,course,score into #temp from
      (   select studentid,studentname,student.classid,classname
          from student right outer join class on student.classid=class.classid) as p
   left outer join score  on p.studentid=score.studentid
select   (select top 1 studentname from  #temp where classname=x.classname and course=x.course order by score  desc) as '姓名',classname as '班级',course as '课程',max(score) as '分数'
       from  #temp x group by classname,course order by classname

 

我自己的答案:

select t.classname,course,max(score) 'score',min(t.studentName) 'studentName' from (select s.studentName,c.classname,r.course,r.score from student s inner join class c on s.classid=c.classid inner join score r on r.studentid=s.studentid ) as t  group by classname,course

posted on 2013-02-17 13:55  笨小孩做开发 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/dullbaby/archive/2013/02/17/2914223.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值