Wednesday, August 29, 2007

Pivot Tables

Example:

SELECT *
FROM (SELECT job,
sum(decode(deptno,10,sal)) DEPT10,
sum(decode(deptno,20,sal)) DEPT20,
sum(decode(deptno,30,sal)) DEPT30,
sum(decode(deptno,40,sal)) DEPT40
FROM scott.emp
GROUP BY job)
ORDER BY 1;
If you are pivoting over varchar fields, you can use the max or min aggregate function because these can operate on varchar fields.

Example:

SELECT language_id,
max(decode(greeting,'hello', sal)) english,
max(decode(greeting,'konichiwa',sal)) japanese,
max(decode(greeting,'ni hao',sal)) chinese,
max(decode(greeting,'ola',sal)) spanish
FROM language.phrases
GROUP BY language_id


References:
How does one code a matrix/crosstab/pivot report in SQL?
Pivot Table Techniques