Based on this question and answer how is the query modified to return the user’s name from a foreign table rather than the id? Here’s the sql from the answer of the linked thread:
SELECT user_id, round(avg(score)::numeric, 2) AS sc_avg
FROM (
SELECT *
, row_number() OVER (PARTITION BY user_id ORDER BY date DESC) AS rn
FROM mg.scores
WHERE score IS NOT NULL
) AS x
WHERE x.rn <= 5
GROUP BY user_id;
2
Answers
You can join then user table to the subselect
First aggregate, then join:
But the best solution depends on undisclosed details. If referential integrity is not guaranteed, you might use a
LEFT JOIN
. If you only want results for a few given users a different query is much more efficient …Especially if some users might not have any scores (yet), this form is the safe course of action (preserving all users):
See:
Either way, have an index on
mg.scores (user_id, date DESC NULLS LAST)
or similar. And onusers (user_id)
. Details depend on the full case.