将多个行和列数据合并为单个连续行

时间:2016-02-12 18:16:37

标签: sql oracle listagg

这是我的表格外观

ID Name1 Name2 Name3
1  a     b       c 
1  c     d       a 
2  d     e       a 
2  c     d       b

我需要每个ID有一行,在一行中有一个不同的name1,name2,name3作为逗号分隔的字符串。

ID Name 
1  a,c,b,d,c 
2  d,c,e,a,b

我尝试使用listagg使用distinct但不能删除重复项。

1 个答案:

答案 0 :(得分:1)

您需要一个子查询来删除重复项,例如;

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           

您也可以让子查询选择所有三列,然后将它们转换为行,但只有三个可能更简单。