1

有一个名为的表,StudentScore其中包含以下字段:Score、和。后面三个是主键。CourseIDStudentIDSemester

我想编写一个存储过程来获取每个学生的平均分数。但是规则相当复杂,我不知道如何在一个查询中表达它。如果可能,应避免嵌套查询。

这是规则:

如果一个学生多次参加一门课程,则只计算最后的分数。

例如,有以下数据:

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

请建议尽可能高效的存储过程。谢谢!

4

1 回答 1

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;
于 2012-08-07T03:43:05.133 回答