SQL(MySQL)每个类别的平均归因于一个人

时间:2016-07-02 11:36:01

标签: mysql sql count average

你好。我会请求帮助解决我的问题。我有这样的建模情况:我有两个表:

学生

ID, FIRST_NAME, LAST_NAME,DATE_OF_BIRTH, CLASS,
1, Petr, Fish, 4.3.1984, 4A
2, John, Stone, 5.5.1990, 4A
3, Jack, Clark, 6.3.1983, 4A
4, George, Field, 5.8.1955, 4A
5, John, Rock, 6.1.1999, 4B
6, Patrick, Light, 1.11.1983, 4B

POINTS_MATH:

STUDENT_ID, POINTS
1, 15
1, 20
2, 30
3, 11
3, 5
4, 3

我需要计算每个班级中一个学生的平均分数(也是空值),所以结果可能如下:

CLASS, AVERAGE_POINTS
4A, 21
4B, 0

非常感谢每个答案

1 个答案:

答案 0 :(得分:0)

根据您的示例,您不需要平均点数,而是所有点数的总和除以学生数量:

 SELECT a.CLASS,
   COALESCE(SUM(p.POINTS) / COUNT(DISTINCT p.STUDENT_ID), 0)
FROM STUDENTS AS s
LEFT JOIN POINTS_MATH AS p ON s.ID = p.STUDENT_ID
GROUP BY c.CLASS

您还可以检查每位学生平均水平是否更符合您的需求:

SELECT s.CLASS, COALESCE(AVG(avgPoints), 0)
FROM STUDENTS AS s
LEFT JOIN 
 (
   SELECT STUDENT_ID, AVG(POINTS) AS avgPoints
   FROM POINTS_MATH
   GROUP BY STUDENT_ID
 ) AS p
ON s.ID = p.STUDENT_ID
GROUP BY s.CLASS