A two-credit 10
- O(n) · Medium
- Full plan
- SQL
- grouping
- joins
- decimals
Problem
Grades go from 0 to 10. Henry has a 10 in Music, an 8 in History, and a 5.5 in Math, and his average is 7.83. The school isn't buying it: Music is worth 2 credits and Math is worth 5. In a weighted average, each grade counts as many times as its course has credits: you add up each grade multiplied by its credits and divide by the total credits. Henry's is 7.15.
For each student with at least one grade entered, show the student_id, the credits already graded, and the weighted average, rounded to 2 decimals, in that order. A course whose grade is still pending adds nothing yet, neither its grade nor its credits.
What it has to return
These rows, in any order
| student_id | graded | weighted |
|---|---|---|
| 1 | 8 | 7.94 |
| 2 | 9 | 7.94 |
| 3 | 10 | 7.15 |
| 4 | 5 | 7 |
| 5 | 9 | 8.44 |
| 6 | 9 | 5.11 |
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 g.student_id, g.grade,
c.credits
FROM grades g
JOIN courses c
ON g.course_id = c.idIt 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) challenges
- Aisle by aisleSQL · grouping · conditionals
- Averages that mean somethingSQL · grouping · joins
- Bunched up or spread outSQL · grouping · joins · sorting
- Chairs for parents' nightSQL · grouping · joins · sorting
- How many payrolls does it cover?SQL · grouping · joins · decimals
- Not the priciest, not the biggestSQL · grouping · joins