I'm creating a report, showing staff members' former teams along with the date they left, aggregated into a single field in the report. This works to a degree:
WITH "most_recent_leave_dates" AS (
SELECT
staff_id, -- alphanumeric string
team,
MAX(date_left) AS "most_recent_date_left"
FROM team_membership
WHERE date_left IS NOT NULL
GROUP BY staff_id, team
-- I thought ordering this CTE would do it, but no
ORDER BY staff_id, most_recent_date_left DESC
)
SELECT
staff_id,
STRING_AGG(
DISTINCT CONCAT(team, ' until ' || most_recent_date_left),
CHR(10) -- separate by newline
) AS "teams"
FROM most_recent_leave_dates
GROUP BY staff_id
https://www.db-fiddle.com/f/jZCcKRWNV8vLJUFsa6kq7/2
But STRING_AGG
is sorting the terms alphabetically. I want them sorted by most_recent_date_left
. How can I do that?
The documentation states:
Alternatively, supplying the input values from a sorted subquery will usually work.
Do I have to rewrite the CTE as a subquery…?