Learn how to converts rows into columns using SQL pivot with Example queries.
The PIVOT operator takes data in separate rows, aggregates it and converts it into columns.
Syntax
SELECT …
FROM …
PIVOT [XML]
( pivot_clause
pivot_for_clause
pivot_in_clause )
WHERE …
pivot_clause: defines the columns to be aggregated (pivot is an aggregate operation)
pivot_for_clause: defines the columns to be grouped and pivoted;
pivot_in_clause: defines the filter for the column(s) in the pivot_for_clause (i.e. the range of values to limit the results to). The
aggregations for each value in the pivot_in_clause will be transposed into a separate column (where appropriate).
A simple example
we will display the no of employees in a separate column for each department, as follows.
SELECT *
FROM (
SELECT DEPTNO
FROM EMP
)
PIVOT
(
COUNT(*) as detp_employees_cnt FOR
DEPTNO IN(10, 20, 30)
);
In the above example query
COUNT(*) is pivot_clause which performs aggregate operation.
DEPTNO is pivot_for_clause which performs group by operation.
10, 20, 30 range of values that transposed into a separate column.
group by operation performs based on the values in pivot_in_clause.
Output
10_DETP_EMPLOYEES_CNT | 20_DETP_EMPLOYEES_CNT | 30_DETP_EMPLOYEES_CNT | |
1 | 3 | 5 | 6 |
Simple Example 2
we will display the Total salary of employees in a separate column for each department, as follows.
SELECT *
FROM
(
SELECT DEPTNO,
SAL
FROM EMP
)
PIVOT
(SUM(SAL) DEPT_TOTAL_SALARY
FOR DEPTNO IN (10,20,30)
);
Output
10_DEPT_TOTAL_SALARY | 20_DEPT_TOTAL_SALARY | 30_DEPT_TOTAL_SALARY | |
1 | 8750 | 10875 | 9400 |
Simple Example 3
SELECT *
FROM
(
SELECT DEPTNO,
/* JOB,*/
SAL
FROM EMP
)
PIVOT
(SUM(SAL) DEPT_TOTAL_SALARY,
count(SAL) DEP_SAL_CNT
FOR DEPTNO IN (10,20,30)
)
Output
10_DEPT_TOTAL_SALARY | 10_DEP_SAL_CNT | 20_DEPT_TOTAL_SALARY | 20_DEP_SAL_CNT | 30_DEP T_TOTAL_SALARY | 30_DEP_SAL_CNT | |
1 | 8750 | 3 | 10875 | 5 | 9400 | 6 |
Simple Example 4
SELECT *
FROM
(
SELECT DEPTNO,
JOB,
SAL
FROM EMP
)
PIVOT
(SUM(SAL) DEPT_SUM,
count(SAL) CNT
FOR (DEPTNO,job) IN ((10,'SALESMAN'),(10,'CLERK'),(10,'MANAGER'))
)
Output
10_’SALESMAN’_DEPT_SUM | 10_’SALESMAN’_CNT | 10_’CLERK’_DEPT_SUM | 10_’CLERK’_CNT | 10 _’MANAGER’_DEPT_SUM | 10_’MANAGER’_CNT | |
1 | 0 | 1300 | 1 | 2450 | 1 |
Simple Example 5
SELECT *
FROM
(
SELECT DEPTNO,EXTRACT( YEAR FROM TO_DATE(HIREDATE,'DD-MM-RRRR')) HIREDATE
FROM EMP
)
PIVOT
(
count(*)
FOR (HIREDATE) IN (1980 AS YEAR_1980,1981 AS YEAR_1981 ,1982 AS YEAR_1982,1983 AS YEAR_1983)
)
Output
DEPTNO | YEAR_1980 | YEAR_1981 | YEAR_1982 | YEAR_1983 | |
1 | 30 | 0 | 6 | 0 | 0 |
2 | 20 | 1 | 2 | 1 | 1 |
3 | 10 | 0 | 2 | 1 | 0 |