First with last
- O(n²) · Very hard
- Full plan
- SQL
- window functions
- joins
- grouping
Problem
The tutor sets up study pairs with the list of averages in hand: whoever has the highest sits with whoever has the lowest, the second with the second to last, and so on toward the middle of the list.
Each student's average is the average of the grades already entered. A pending grade doesn't count, and a student with no grades entered is left out of the pairing. Lucas and Emma have the same average: between two equals, whoever comes first alphabetically goes first on the list.
Show one row per pair, with the name of whoever is higher on the list and then their partner's name, sorted alphabetically by the name in the first column. If the list has an odd number of students, whoever lands in the middle has nobody to sit with: that student gets a row too, with the second cell empty.
What it has to return
These rows, in this order
| name | partner |
|---|---|
| Emma | Lucas |
| Henry | Julia |
| Megan | Leo |
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 s.name,
AVG(g.grade) AS average
FROM grades g
JOIN students s
ON g.student_id = s.id
GROUP BY s.id, s.name
ORDER BY average DESCIt 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
- How soon they're backSQL · window functions · dates · grouping
- January off the shelfSQL · dates · nulls · grouping
- Lighthouse, TheSQL · strings · conditionals · sorting
- One raise, not twoSQL · changing data · conditionals
- Out of every 100 in payrollSQL · window functions · decimals
- Paige is leavingSQL · changing data · subqueries