这个问题是在csdn上一位朋友写的,但是答案有点复杂,而且查询使用的效率也不是很好,于是自己也写了一个。以下是表结构和数据,
有以下两张表,Class表 classid classname1 高三(一)班2 高三(二)班3 高三(三)班Student表studentid studentName classid1 张三 22 李四 13 王五 14 赵六 35 钱七 26 孙九 3score表scoreid course studentid score1 数学 2 992 数学 3 603 数学 4 804 语文 5 795 语文 6 586 语文 1 667 英语 6 768 英语 4 879 英语 3 10010 英语 2 69编写SQL语句查询出每个各科班分数最高的同学的名字,班级名称,课程名称,分数(问题有点绕口)
朋友的答案:
if exists(select count(*) from sysobjects where type='U' and name='#temp') drop table #tempselect 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.studentidselect (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
这个问题是在csdn上一位朋友写的,但是答案有点复杂,而且查询使用的效率也不是很好,于是自己也写了一个。以下是表结构和数据,
有以下两张表,Class表 classid classname1 高三(一)班2 高三(二)班3 高三(三)班Student表studentid studentName classid1 张三 22 李四 13 王五 14 赵六 35 钱七 26 孙九 3score表scoreid course studentid score1 数学 2 992 数学 3 603 数学 4 804 语文 5 795 语文 6 586 语文 1 667 英语 6 768 英语 4 879 英语 3 10010 英语 2 69编写SQL语句查询出每个各科班分数最高的同学的名字,班级名称,课程名称,分数(问题有点绕口)
朋友的答案:
if exists(select count(*) from sysobjects where type='U' and name='#temp') drop table #tempselect 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.studentidselect (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