读书人

Oracle 多行转列步骤

发布时间: 2012-07-29 15:26:13 作者: rapoo

Oracle 多行转列方法
Creating a comma-separated list in SQL

For some reason I can never understand, one of the most-asked Oracle questions on the Web goes something like this:

It is self-contained, as no PL/SQL functions or object types are required, and The results are ordered.

The following example illustrates the technique using the SCOTT demo table "emp":2

SELECT deptno      , LTRIM(SYS_CONNECT_BY_PATH(ename,','))FROM   ( SELECT deptno              , ename              , ROW_NUMBER() OVER (PARTITION BY deptno ORDER BY ename) -1 AS seq          FROM   emp ) WHERE  connect_by_isleaf = 1CONNECT BY seq = PRIOR seq +1 AND deptno = PRIOR deptno START WITH seq = 1;    DEPTNO CONCATENATED---------- --------------------------------------------------        10 CLARK,KING,MILLER        20 ADAMS,FORD,JONES,SCOTT,SMITH        30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD3 rows selected.

Another approach involves harnessing the dark power of XML:3

SELECT deptno     , RTRIM       ( xmlagg (xmlelement (c, ename || ',') order by ename).extract ('//text()')       , ',' ) AS concatenatedFROM   empGROUP BY deptno;    DEPTNO CONCATENATED---------- ---------------------------        10 CLARK,KING,MILLER        20 ADAMS,FORD,JONES,SCOTT,SMITH        30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD3 rows selected.

读书人网 >其他数据库

热点推荐