comma-separated list as a result of select statement in Oracle [duplicate]

倾然丶 夕夏残阳落幕 提交于 2019-11-27 22:35:57
SELECT parent_id,
       RTRIM(XMLAGG(XMLELEMENT(e,child_id || ',')).EXTRACT('//text()'),',') AS "Children"
  FROM parentChildTable
 WHERE parent_id = 0
 GROUP BY parent_id

or

SELECT parent_id,
       LISTAGG(child_id, ',') WITHIN GROUP (ORDER BY child_id) AS "Children"
  FROM parentChildTable
 WHERE parent_id = 0
 GROUP BY parent_id

Mark's implementation of LISTAGG is definitely the way to go for ORacle 11GR2. For For 11GR1 or Oracle 10 you can use wmsys.wm_Concat instead in exactly the same way (may require a permissions grant from your DBA)

Just another way to approach it ...

SELECT parent_id,max(child_list) FROM (
  SELECT parent_id,sys_connect_by_path(child_number,',') child_list FROM (
    SELECT parent_id, id,
           row_number() over (partition by parent_id order by id) child_number
      FROM person
      WHERE parent_id IS NOT NULL
  )
  START WITH child_number=1
  CONNECT BY parent_id = PRIOR parent_id AND child_number = PRIOR child_number + 1
)
GROUP BY parent_id
ORDER BY parent_id
;

SELECT wmsys.wm_concat() FROM ;

It's controversial, but it works - https://forums.oracle.com/forums/thread.jspa?threadID=2205545

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!