potato300 potato300 - 5 months ago 9
SQL Question

SQL query to return average

I have table

grades
:

id | student_id | grade
-----------------------
1 | 1 | 4
2 | 1 | 5
3 | 2 | 3


I want a query that returns
student_id
and average
grade
:

student_id | avg_grade
----------------------
1 | 4.5
2 | 3


What query would do that?

Answer

SQL's AVG() function does that:

SELECT student_id, AVG(grade) as avg_grade
FROM grades
GROUP BY student_id

Reference for MySQL's AVG()