21 January 2014

Oracle sql rows to columns transpose

Use any of the following SQL to transpose rows into a single column

SQL 1
SELECT substr(XMLAGG (XMLELEMENT ("T", e.job||',')).EXTRACT ('//text()') ,1,length(XMLAGG (XMLELEMENT ("T", e.job||',')).EXTRACT ('//text()'))-1)
  FROM emp e

More documentation on XMLAGG  function :

http://docs.oracle.com/cd/B19306_01/server.102/b14200/functions215.htm
SQL 2

SELECT LISTAGG(e.job, ', ') WITHIN GROUP (ORDER BY 1)
  FROM emp e

More documentation on LISTAGG function :  http://docs.oracle.com/cd/E11882_01/server.112/e17118/functions089.htm#SQLRF51487

No comments: