Write SQL query to concatenate strings from multiple rows into a single row value?
#ORACLE
with cte as (
select 1 as id, 'A' as name from dual union
select 1 as id, 'B' as name from dual union
select 1 as id, 'C' as name from dual union
select 2 as id, 'D' as name from dual union
select 2 as id, 'E' as name from dual union
select 3 as id, 'F' as name from dual union
select 3 as id, NULL as name from dual union
select 4 as id, 'G' as name from dual
)
SELECT ID,LISTAGG(NAME, ',') WITHIN GROUP (ORDER BY ID) NEW_NAME FROM CTE GROUP BY ID;
#MYSQL
with cte as (
select 1 as id, 'A' as name union ALL
select 1 as id, 'B' as name union ALL
select 1 as id, 'C' as name union ALL
select 2 as id, 'D' as name union ALL
select 2 as id, 'E' as name union ALL
select 3 as id, 'F' as name union ALL
select 3 as id, NULL as name union ALL
select 4 as id, 'G' as name
)
SELECT ID,GROUP_CONCAT(NAME SEPARATOR ';') AS NEW_NAME FROM CTE GROUP BY ID;
#POSTGRESQL
with cte as (
select 1 as id, 'A' as name union ALL
select 1 as id, 'B' as name union ALL
select 1 as id, 'C' as name union ALL
select 2 as id, 'D' as name union ALL
select 2 as id, 'E' as name union ALL
select 3 as id, 'F' as name union ALL
select 3 as id, NULL as name union ALL
select 4 as id, 'G' as name
) SELECT ID,STRING_AGG(NAME ,',' ORDER BY ID) AS NEW_NAME FROM CTE GROUP BY ID
#SQLSERVER
with cte as (
select 1 as id, 'A' as name union ALL
select 1 as id, 'B' as name union ALL
select 1 as id, 'C' as name union ALL
select 2 as id, 'D' as name union ALL
select 2 as id, 'E' as name union ALL
select 3 as id, 'F' as name union ALL
select 3 as id, NULL as name union ALL
select 4 as id, 'G' as name
) SELECT ID,STRING_AGG(NAME ,',' ) AS NEW_NAME FROM CTE GROUP BY ID
0 Comments
Thanks for your message.