串联并在Oracle的组的多个行[复制](Concatenate and group multipl

2019-06-18 06:49发布

可能重复:
如何检索一个Oracle中两列数据,B格式

假设我有一个像这样的表:

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

我想有这样的结果:

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

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

Concatatenating一个栏表:

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不可用。

Answer 1:

考虑使用LISTAGG功能的情况下,你是11g上:

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



文章来源: Concatenate and group multiple rows in Oracle [duplicate]