考虑以下架构。
学生:
StudentID uniqueidentifier
Name varchar(max)
FKTeacherID uniqueidentifier
TestScore:
TestScoreID uniqueidentifier
Score int
FKStudentID uniqueidentifier
我的目标是编写一个查询,以获得每位教师的最高考试成绩和达到该成绩的学生。返回教师的ID(Student.FKTeacherID),获得的分数(TestScore.Score)和实现它的学生(Student.Name)。
我可以写这样的东西来获得前两个必需的列:
SELECT FKTeacherID, MAX(Score) MaxScore
FROM Student
JOIN TestScore on FKStudentID = StudentID
GROUP BY FKTeacherID
但我无法在不将其添加到group by子句的情况下获取相关的Student.Name,这将更改结果集。
答案 0 :(得分:2)
如果我理解正确,一个选项是使用row_number()
- 这是一个带有common-table-expression的例子:
with cte as (
select s.fkteacherid,
ts.score,
s.name,
row_number() over (partition by s.fkteacherid order by ts.score desc) rn
from student s
inner join testscore ts on s.studentid = ts.fkstudentid
)
select fkteacherid, score, name
from cte
where rn = 1
基本想法是按fkteacherid
分组,按每个组中的score desc
排序,并从每个组中获取第一条记录。
答案 1 :(得分:0)
<强>更新强>
请尝试更新的查询:
SELECT
FKTeacherID, Name, Score
FROM
Student
JOIN TestScore on FKStudentID = StudentID
JOIN
(
SELECT
B.FKTeacherID AS TeacherID, MAX(A.Score) MaxScore
FROM
Student B
JOIN TestScore A on A.FKStudentID = B.StudentID
GROUP BY
B.FKTeacherID
) As TeachersMaxScore
ON TeachersMaxScore.TeacherID = FKTeacherID
AND TeachersMaxScore.MaxScore = Score