将多行和多列数据合并为单个串联行
Merging multiple rows and column data into single concatenated row
这是我的 table 的样子
ID Name1 Name2 Name3
1 a b c
1 c d a
2 d e a
2 c d b
我需要每个 ID 一行,在一行中有不同的名称 1、名称 2、名称 3 作为逗号分隔的字符串。
ID Name
1 a,c,b,d,c
2 d,c,e,a,b
我试过使用具有不同但无法删除重复项的 listagg。
您需要一个子查询来删除重复项,例如;
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 代表您的演示 table:
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
您也可以让子查询选择所有三列,然后将它们旋转成行,但只有三列这可能更简单。
这是我的 table 的样子
ID Name1 Name2 Name3
1 a b c
1 c d a
2 d e a
2 c d b
我需要每个 ID 一行,在一行中有不同的名称 1、名称 2、名称 3 作为逗号分隔的字符串。
ID Name
1 a,c,b,d,c
2 d,c,e,a,b
我试过使用具有不同但无法删除重复项的 listagg。
您需要一个子查询来删除重复项,例如;
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 代表您的演示 table:
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
您也可以让子查询选择所有三列,然后将它们旋转成行,但只有三列这可能更简单。