您需要一个子查询来删除重复项,例如;
select id, listagg(name, ',') within group (order by name) as names
from (
select id, name1 as name from your_table
union
select id, name2 as name from your_table
union
select id, name3 as name from your_table
)
group by id
union 会自动从组合结果集中删除重复项(如果您不希望这样做,可以使用 union all)。
作为一个带有代表您的表格的 CTE 的演示:
with your_table(id, name1, name2, name3) as (
select 1, 'a', 'b', 'c' from dual
union all select 1, 'c', 'd', 'a' from dual
union all select 2, 'd', 'e', 'a' from dual
union all select 2, 'c', 'd', 'b' from dual
)
select id, listagg(name, ',') within group (order by name) as names
from (
select id, name1 as name from your_table
union
select id, name2 as name from your_table
union
select id, name3 as name from your_table
)
group by id;
ID NAMES
-- --------------------
1 a,b,c,d
2 a,b,c,d,e
您也可以让子查询选择所有三列,然后将它们转为行,但只有三列这可能更简单。