【问题标题】:Merging multiple rows and column data into single concatenated row将多行和多列数据合并为单个连接行
【发布时间】:2016-02-12 18:16:36
【问题描述】:

这是我的桌子的样子

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。

【问题讨论】:

    标签: sql oracle listagg


    【解决方案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           
    

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

    【讨论】:

    • 谢谢亚历克斯。我不知道为什么我以前没有想到这一点。这有效!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-14
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    相关资源
    最近更新 更多