有一个名为StudentScore
的表格,其中包含以下字段:Score
,CourseID
,StudentID
和Semester
。后三个是主键。
我想写一个存储过程来获得每个学生的平均分数。但规则相当复杂,我不知道如何在一个查询中表达它。如果可能,应该避免使用嵌套查询。
以下是规则:
如果一名学生多次参加课程,则只应计算最后一个分数。
例如,有以下数据:
StudentID | CourseID | Semester | Score
1 1 1 80
1 2 1 40
1 3 1 60
1 2 2 50
1 3 2 20
2 1 1 90
存储过程应返回:
StudentID | AvgScore
1 50 // which is avg(80, 50, 20)
2 90
请尽可能高效地建议存储过程。谢谢!
答案 0 :(得分:2)
;WITH x AS
(
SELECT StudentID, Score, rn = ROW_NUMBER() OVER
(PARTITION BY StudentID, CourseID
ORDER BY Semester DESC)
FROM dbo.StudentScore
)
SELECT StudentID, AvgScore = AVG(Score)
FROM x
WHERE rn = 1
GROUP BY StudentID;
如果你想要四舍五入到某些小数位的东西,可能是:
;WITH x AS
(
SELECT StudentID, Score = 1.0*Score, rn = ROW_NUMBER() OVER
(PARTITION BY StudentID, CourseID
ORDER BY Semester DESC)
FROM dbo.StudentScore
)
SELECT StudentID, AvgScore = CONVERT(DECIMAL(10,2), AVG(Score))
FROM x
WHERE rn = 1
GROUP BY StudentID;