I have the following tables:
Teammate ID | Teammate name | Team id | Teams |
---|---|---|---|
1 | Amy | 11 | Sales |
1 | Amy | 12 | Support |
1 | Amy | 13 | Marketing |
2 | Peter | 12 | Support |
2 | Peter | 13 | Marketing |
And I want to group my results so the Teams column appears in one single row by Teammate Id or Teammate name as per below:
Teammate ID | Teammate name | Team id | Teams |
---|---|---|---|
1 | Amy | 11, 12, 13 | Sales, Support, Marketing |
2 | Peter | 12, 13 | Support, Marketing |
Which function would be best/cleanest to use for this purpose? I tried subqueries, coalescing, some weird XML path thing but as a new SQL user I can’t wrap my head around figuring this one out
My original query which gave me the results is;
SELECT
tm.teammate_id AS "Teammate ID",
tm.name AS "Teammate name",
itt.team_id AS "Team IDs",
it.team AS "Teams"
FROM
intercom_teammates AS tm
LEFT JOIN intercom_teammate_teams AS itt
ON tm.teammate_id = itt.teammate_id
LEFT JOIN intercom_teams AS it
ON tm.teammate_id = itt.teammate_id
2
Answers
A simple group_concat would do the trick:
https://dbfiddle.uk/rU8-h8rX
Note. I used distinct on Teammatename, but I think it is excess and you can remove it if for every different TeammateID the Teammatename is unique.
Note: I’ve corrected your
JOIN
tointercom_teams
changingitt.teammate_id
toit.teammate_id
; it was throwing off the result set.Result:
Fiddle here.