问题
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