在Oracle中连接并分组多行

时间:2012-09-24 03:32:47

标签: sql oracle concatenation grouping group-concat

  

可能重复:
  how to retrieve two columns data in A,B format in Oracle

假设我有一个这样的表:

NAME          GROUP_NAME
name1         groupA
name2         groupB
name5         groupC
name4         groupA
name3         groupC

我想得到这样的结果:

GROUP_NAME     NAMES
groupA         name1,name4
groupB         name2
groupC         name3,name5

如果表中只有一列,我可以通过执行以下操作来连接记录,但是在上下文中进行分组时,我真的没有太多想法。

连接一个列表:

SELECT names 
FROM (SELECT SYS_CONNECT_BY_PATH(names,' ') names, level
      FROM name_table

      START WITH names = (SELECT names FROM name_table WHERE rownum = 1)
      CONNECT BY PRIOR names < names
      ORDER BY level DESC)
      WHERE rownum = 1 

更新

我现在有一个使用LISTAGG

的解决方案
SELECT
group_name,
LISTAGG(name, ', ')
WITHIN GROUP (ORDER BY GROUP) "names"
FROM name_table
GROUP BY group_name

对于LISTAGG不可用的情况,仍然对更“一般”的解决方案感兴趣。

1 个答案:

答案 0 :(得分:60)

如果您使用的是11g,请考虑使用LISTAGG功能:

select grp, listagg(name,',') within group( order by name ) 
  from name_table group by grp

sqlFiddle

upd:如果您不是,请考虑使用分析:

select grp,
    ltrim(max(sys_connect_by_path
       (name, ',' )), ',')
        scbp
  from (select name, grp,
            row_number() over
           (partition by grp
            order by name) rn
         from tab
          )
start with rn = 1
connect by prior rn = rn-1
and prior grp = grp
  group by grp
  order by grp

sqlFiddle