问题描述
嗨,我很想查询连接表,但我无法弄清楚。 如何找到特定课程中得分最高的五个学生
CREATE TABLE Students (
StudentID int NOT NULL PRIMARY KEY,LastName varchar(255) NOT NULL,FirstName varchar(255) NOT NULL,StudentNum int NOT NULL,);
CREATE TABLE Courses (
CourseID int NOT NULL PRIMARY KEY,CourseName varchar(255) NOT NULL,GPA int(255) NOT NULL
);
CREATE TABLE University (
StudentID int NOT NULL,CourseID int NOT NULL,CONSTRAINT PK_University PRIMARY KEY
(
StudentID,CourseID
),FOREIGN KEY (StudentID) REFERENCES Students (StudentID),FOREIGN KEY (CourseID) REFERENCES Courses (CourseID)
);
解决方法
我将分数字段添加到 University
表并将大学名称更改为 Students_Courses
。
首先将大学表更改为:
CREATE TABLE Students_Courses (
StudentID int NOT NULL,CourseID int NOT NULL,Score float,CONSTRAINT PK_Students_Courses PRIMARY KEY
(
StudentID,CourseID
),FOREIGN KEY (StudentID) REFERENCES Students (StudentID),FOREIGN KEY (CourseID) REFERENCES Courses (CourseID)
);
现在您可以join
表格并按分数排序并找到最高分中的 5 个。
你可以使用
select top 5 s.StudentID,s.FirstName,s.LastName,sc.Score,c.CourseName
from Students_Courses sc join Students s on sc.StudentID = s.StudentID
join Courses c on sc.CourseID = c.CourseID
where sc.CourseID = 1
order by Score desc
或
select top 5 s.StudentID,sc.Score
from Students_Courses sc join Students s on sc.StudentID = s.StudentID
where sc.CourseID = 1
order by Score desc
或使用窗口函数
select StudentID,FirstName,LastName,Score
from
(select s.StudentID,ROW_NUMBER() over(order by sc.Score desc) as seq
from Students_Courses sc join Students s on sc.StudentID = s.StudentID
where sc.CourseID = 1) T
where seq <= 5
dbfiddle 中的演示