I have 2 related tables as given below where I need to concatenate the names of group members into a query result as given below:
I am not sure whether this is possible with SQL. I tried to use group by
, but I do not know a useful expression to search for concatenation
in the context of group by
. Any hints where and with what key words to search for will be gratefully appreciated.
CodePudding user response:
use String_agg
as follows
SELECT groupid,
groupname,
String_agg(groupmembername, ',') AS GroupMemberName
FROM lefttable1 t1
JOIN righttable2 t2
ON t1.groupid = t2.groupid
GROUP BY groupid,
groupname
or as follows
SELECT groupid,
groupname,
String_agg(groupmembername, ',') AS GroupMemberName
FROM (SELECT groupid,
groupname,
groupmembername
FROM lefttable1 t1
JOIN righttable2 t2
ON t1.groupid = t2.groupid) T3