首页 > 数据库 > Oracle > Oracle Pivot examples
Answer: The function PIVOT transposes rows in columns and the function UNPIVOT transposes columns in rows. They have been added in 11g.
WITH
T
AS
(
SELECT
DEPTNO
FROM
EMP
)
SELECT
*
FROM
T
PIVOT
(
COUNT(*)
FOR
(DEPTNO)
IN
(10,20,30,40)
);
10 20 30
40
---------- ---------- ---------- ----------
3 5 6 0
----------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
----------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 52 | 3 (0)| 00:00:01 |
| 1 | VIEW | | 1 | 52 | 3 (0)| 00:00:01 |
| 2 | SORT AGGREGATE | | 1 | 3 | | |
| 3 | TABLE ACCESS FULL| EMP | 14 | 42 | 3 (0)| 00:00:01 |
----------------------------------------------------------------------------
Four columns are created for the departments 10, 20, 30 and 40.
For each column, the number of corresponding rows is counted.
Compare with:
SELECT
DEPTNO,
COUNT(*)
FROM
EMP
GROUP BY
DEPTNO;
DEPTNO COUNT(*)
---------- ----------
30 6
20 5
10 3
In the first statement, one row is returned with all departments. In the
second statement each department is on a different row. The columns that are not
aggregated and not pivoted will return multiple rows:
WITH
T
AS
(
SELECT
DEPTNO,
JOB,
SAL
FROM
EMP
)
SELECT
*
FROM
T
PIVOT
(
MIN(SAL) AS MINSAL,
MAX(SAL) AS MAXSAL
FOR
(JOB)
IN
(
'CLERK' AS CLERK,
'SALESMAN' AS SALES
)
)
ORDER BY
DEPTNO;
DEPTNO CLERK_MINSAL
CLERK_MAXSAL SALES_MINSAL SALES_MAXSAL
---------- ------------ ------------ ------------ ------------
10 1300 1300
20 800 1100
30 950 950 1250 1600
Three rows are selected. The job is the pivot, the salaries are aggregated and the departments are returned as distinct rows. Note the different values for the pivot are explicitly listed.
The inline view T contains three columns, the salary is aggregated, the job is transposed into multiple columns, and the remaining column is used as a group for the aggregation. The remaining column is the department, which contains three distinct values; each value returns exactly one row. To specify the group by the department, it is therefore necessary to select only the department in addition to the aggregated values and to the transposed column.
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/20864683/viewspace-2094168/ ,如需转载,请注明出处,否则将追究法律责任。