Thursday, April 17, 2008

CUBE function and Pivot Table in SQL

I am currently working on a new OA component, pivot table. To mimic the pivot table in Microsoft Excel, I decided to design the functionality in Java rather than using Oracle's powerful CUBE functionality. I can definitely blog about the reasons behind this decision later, but I am overwhelmed by the power of using CUBE and decided to ramble something about it.

1. Its syntax is very simple
2. Its pretty fast

Illustration:

select e.dept_no, e.job_type, e.salary
from emp_table e

DEPT_NO JOB_TYPE SALARY
---------------------------------------
10 Manager 10,000
10 Clerk 3,000
10 Clerk 4,000
20 Manager 12,000
20 Clerk 3,000
20 Clerk 5,000
20 Foreman 1,000


Say we want to see a tabular information of sum of salary for department wise and again group on it based on job type

select e.dept_no, e.job_type, sum(e.salary)
from emp_table e
group by cube(e.dept_no, e.job_type)

DEPT_NO JOB_TYPE SALARY
---------------------------------------
Manager 22,000
Clerk 15,000
Foreman 1,000
10 Manager 10,000
10 Clerk 7,000
10 Foreman 0
10 17,000
20 Manager 12,000
20 Clerk 8,000
20 Foreman 1,000
20 21,000
38,000



Now we can use the famous pivoting technique in SQL to get the same information like Excel.

select nvl(job_type, 'Grand Total') JOB_TYPEX
decode(dept_no,10,max(s),0) DEPT_10,
decode(dept_no,20,max(s),0) DEPT_20,
decode(nvl(dept_no,-999),-999,max(s),0) ALL_DEPT
from (select e.dept_no, e.job_type, sum(e.salary) s
from emp_table e
group by cube(e.dept_no, e.job_type))
group by job_type
order by job_type

JOB_TYPEX DEPT_10 DEPT_20 ALL_DEPT
-----------------------------------------
Clerk 7,000 8,000 15,000
Foreman 0 1,000 1,000
Manager 10,000 12,000 22,000
Grand Total 17,000 21,000 38,000

But the problem is that, we must know all departments to pivot it.

No comments: