SQL为学生选择平均成绩

时间:2015-08-14 20:44:04

标签: mysql average

我正在学习SQL,我遇到了一些麻烦, 我需要每个学生的平均成绩。

我做了下表。

students
|id_student|name|

subjects
|id_subject|name|

grades
|id_grade|value|

我使用这些表链接它们:

students_subjects
|id_student|id_subject|

subjects_grades
|id_subject|id_grade|

students_grades
|id_student|id_grade|

任何帮助表示赞赏

我正在尝试

SELECT students.name, subjects.name, grades.value
FROM students
INNER JOIN students_subjects
ON students.id_student = students_subjects.id_student
INNER JOIN subjects
ON subjects.id_subject = students_subjects.id_subject
INNER JOIN students_grades
ON students_grades.id_student = students.id_student
INNER JOIN grades
ON students_grades.id_grade = grades.id_grade
INNER JOIN subjects_grades
ON grades.id_grade = subjects_grades.id_grade

我得到下表

|     name |    name | value |
|----------|---------|-------|
|     Nico |  class1 |    70 |
|     Nico |  class1 |    40 |
|     Nico |  class2 |    70 |
|     Nico |  class2 |    40 |
|    Fadia |  class1 |    60 |
|    Fadia |  class1 |    55 |
| Cristian |  class2 |    50 |
| Cristian |  class2 |    40 |

但如果我做AVG(grade.value),我只会得到第一行

1 个答案:

答案 0 :(得分:0)

只需添加一个组:

SELECT students.name, subjects.name, AVG(grades.value)
FROM students
    INNER JOIN students_subjects
    ON students.id_student = students_subjects.id_student
    INNER JOIN subjects
    ON subjects.id_subject = students_subjects.id_subject
    INNER JOIN students_grades
    ON students_grades.id_student = students.id_student
    INNER JOIN grades
    ON students_grades.id_grade = grades.id_grade
    INNER JOIN subjects_grades
    ON grades.id_grade = subjects_grades.id_grade
GROUP BY students.name, subjects.name