Home > Mobile >  Use STRING_AGG to get Values from 3 different Tables
Use STRING_AGG to get Values from 3 different Tables

Time:01-25

I am trying to get comma-separated values from the following 3 tables:

Teams: Id

Players: Id, Name

TeamsPlayers: Id, TeamId, PlayerId

What I am trying to get is a result like this:

TeamId PlayerNames
1 Ronaldo,Rivaldo,Ronaldinho,Dida
2 Riquelme,Messi,Aguero,DiMaria
sql

SELECT STRING_AGG(Name, ',')
FROM (
    SELECT tp.TeamId, p.Name
    FROM Players p
    JOIN TeamPlayers tp ON p.Id = tp.PlayerId
    GROUP BY tp.TeamId, p.Name
    )

CodePudding user response:

Expanding on Larnu's comment.

Asssuming your initial query has the proper elements

SELECT tp.TeamId, 
      ,Names = STRING_AGG(p.Name, ',')
 FROM  Players p
 JOIN TeamPlayers tp ON p.Id = tp.PlayerId
 GROUP BY tp.TeamId
  • Related