How to convert rows to columns in Oracle SQL

好久不见. 提交于 2019-12-25 01:09:15

问题


For a requirement I have to create a query to show Employees Schedule per week. Query is like this:

select weekday, sched_hrs
  from table
 where emplid = '12345'
   and weekday_name= 1

Output of this query is like:

Weekday |  Sched_hrs
-------------------- 
   1    |    7.6
   1    |    7.6
   1    |    7.6
   1    |    7.6
   1    |    7.6
   1    |    OFF
   1    |    OFF

I want the output in below format:

1   7.6  7.6   7.6   7.6   7.6   OFF  OFF

How to achieve it?


回答1:


If you are OK with concatenated list, then use LISTAGG which was introduced in Oracle 11g Release 2.

SELECT weekday, LISTAGG(Sched_hrs, ',') WITHIN GROUP (ORDER BY weekday) AS Sched_hrs
FROM   table 
 WHERE emplid = '12345' AND weekday_name= 1
GROUP BY weekday;

For example,

SQL> column employees format a50
SQL> SELECT deptno, LISTAGG(ename, ',') WITHIN GROUP (ORDER BY ename) AS employees
  2  FROM   emp
  3  GROUP BY deptno;

    DEPTNO EMPLOYEES
---------- --------------------------------------------------
        10 CLARK,KING,MILLER
        20 ADAMS,FORD,JONES,SCOTT,SMITH
        30 ALLEN,BLAKE,JAMES,MARTIN,TURNER,WARD

SQL>



回答2:


In 11g you can use the PIVOT function. See the documentation:

http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html



来源:https://stackoverflow.com/questions/28557467/how-to-convert-rows-to-columns-in-oracle-sql

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