1、pivot的格式
select from
( inner_query )
pivot(aggreate_function for pivot_column in ( list of values))
order by ...;
2、轉換單個列
select
from (
select month, prd_type_id, amount
from all_sales
)
pivot (sum(amount) for month in (
1 as JAN,
2 as FEB,
3 as MAR,
4 as APR)
)
order by prd_type_id
3、转换多个列
select *
from ( select month,
prd_type_id,
amount
from all_sales)
pivot ( sum(amount) for (month, prd_type_id)
in ( (1,2) as JAN_P2,
(2,3) as FEB_P3)
);
4、转换中使用多个聚合函数
select *
from ( select cust_no,
mag_man_cert_type,
t.mag_man_cert_no,
mag_man_type
from L_CIF_ENT_CUST_MAG_MAN_INFO t)
pivot ( max(mag_man_cert_NO) as no ,
max(mag_man_cert_type) as type
for mag_man_type In ( ‘01‘ as GLR01,
‘02‘ as GLR02,
‘03‘ as GLR03)
);
转一篇比较好的文章:
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
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.