Home > Blockchain >  How to concatenate group members into a resulting column of an SQL query
How to concatenate group members into a resulting column of an SQL query

Time:03-13

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:

enter image description here

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  
  • Related