有三张表,如下:
--学生表
SELECT TOP 1 * FROM dbo.student
--课程表
SELECT TOP 1 * FROM dbo.course
--成绩表
SELECT TOP 1 * FROM dbo.Score
如何查出每一门课程的最高分对应的学生的姓名,课程名称,分数?
--以下是我做的,得出最高分之后怎么和student表联系起来呢 困惑中...
SELECT MAX(score) ,CourseId
FROM dbo.Score
GROUP BY CourseId
自己使用了如下的方法:
SELECT dbo.student.NAME,b.BCourseName,b.BScore FROM dbo.student,
(SELECT C.CourseId AS BCourseID,C.CourseName AS BCourseName,A.MS AS BScore FROM dbo.course AS C,
(
SELECT MAX(score) AS MS,
CourseId AS cid
FROM dbo.Score s
GROUP BY s.CourseId
) AS A
WHERE c.CourseId=a.cid )
AS B
,dbo.Score
WHERE dbo.student.StudentId=score.StudentID AND score.CourseId=b.BCourseID AND score.score=b.BScore
GROUP BY b.BCourseName,b.BScore,dbo.student.NAME ORDER BY B.BScore DESC
1.先对Score表按courseID分组得到MAx(Score),作为表A(CourseID,MS)
2.表A和表course联合得到对应的课程名,作为表B(BCourseID,BcourseName,BScore)
3.以表B里的BCourseID和BScore作为条件,再次联结Score表得到每一个课程对应的StudentID(这个地方会有问题吗?),再联结Student表即可得到学生名
感觉这样的做效率很低,联结了两次Score表,有好的方法吗?
其实,不难,你从score表中,按照课程找出max_score和 coursedID,然后再和score表join,找到StudentID,再和Student 进行join就行,代码是
select * from dbo.Score s inner join( select max(score) as max_score,CourseID from dbo.Score group by CourseID ) as t on s.CourseID=t.CourseID and s.score=t.max_score) inner join dbo.Student st on s.studentid=st.studentid
刚才在写问题补充,和您给的思路有点像,这样的效率会很低吗,联结了两次Score表
@~扎克伯格: 你给的那个不好使啊 最后那一句having Max(score)
@橘生淮南_: 已修改,更新了
@橘生淮南_: 这是一种思路啦,在写法上可以变,你看看,执行的性能,其实,不会很低
1 select S.NAME,C.CourseName, SC.score from score SC inner join course C on SC.CourseId=C.CourseId inner join student S on SC.StudentID=S.StudentId where SC.score in (select max(score) from score group by CourseID)
通过dbo.Score表中的studentId 与studnet 表中的studentId 关联起来就行了
百度:分组取第一
三表关联,所以三者互相之间有关联列,利用关联列,其实并不难。如果想要性能提升一些,在索引上注意SQL的写法,通过user_indexes和user_ind_columns两个数据字典查看该表的相关索引及索引列,在索引列上进行查询,性能才会有所提高(小表就不用了,在这儿指的是大表)。
select a.name,b.coursename c.score from student a,corse b,score c where a.studentid=c.studentid and b.course_id=c.course_id and a.student_id in (select max(score),c.studentid from score c group by courseid);