Skip to the content

One student, one vote

Problem

The vice principal isn't sold on the average for each year. Grades go from 0 to 10. Pooling every third-year grade gives 7.1, but in that calculation Megan, who has three grades, counts for more than Leo, who has two. The vice principal wants it done another way: first each student's average, and then the average of those averages, so every student counts the same. Done that way, third year comes to 6.79.

Show the year and that average, rounded to 2 decimals, in that order. Round only at the end: each student's average goes into the calculation with all its decimals.

A grade that hasn't been entered doesn't go into anyone's average. And a student with no grades entered has no average: that's not a zero, and it stays out of the average for their year.

What it has to return

These rows, in any order

yearyear_avg
17.75
27.42
36.79

This is what comes out with the data in the practice database this challenge uses. The column names don’t count, so name yours however you like: what counts is how many there are and the order they come in. Besides this one, the challenge has hidden tests with other data that are revealed when you submit your solution.

You start with this

SQL

SELECT student_id,
  AVG(grade) AS average
FROM grades
GROUP BY student_id;
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →