取最近一组的平均值

时间:2012-08-07 03:32:26

标签: sql-server stored-procedures

有一个名为StudentScore的表格,其中包含以下字段:ScoreCourseIDStudentIDSemester。后三个是主键。

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

以下是规则:

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

例如,有以下数据:

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

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

1 个答案:

答案 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;