Skip to the content

First with last

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

namepartner
EmmaLucas
HenryJulia
MeganLeo

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 DESC
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²) challenges

See all challenges →