Powered By Blogger

Wednesday, April 6, 2011

Pivot Query in Oracle 11g

Thanks Vijay ...

SQL> SELECT *
  2    FROM (SELECT job, deptno, sum(sal) sal FROM emp GROUP BY job, deptno)
  3           PIVOT ( sum(sal) FOR deptno IN (10, 20, 30, 40) );

JOB               10         20         30         40
--------- ---------- ---------- ---------- ----------
CLERK           1300       1900        950
SALESMAN                              5600
PRESIDENT       5000
MANAGER         2450       2975       2850
ANALYST                    6000

SQL> SELECT  *
  2    FROM  (SELECT job,
  3                  sum(decode(deptno,10,sal)) DEPT10,
  4                  sum(decode(deptno,20,sal)) DEPT20,
  5                  sum(decode(deptno,30,sal)) DEPT30,
  6                  sum(decode(deptno,40,sal)) DEPT40
  7             FROM scott.emp
  8         GROUP BY job)
  9  ORDER BY 1;

JOB           DEPT10     DEPT20     DEPT30     DEPT40
--------- ---------- ---------- ---------- ----------
ANALYST                    6000
CLERK           1300       1900        950
MANAGER         2450       2975       2850
PRESIDENT       5000
SALESMAN                              5600

Regards,
Navaneeth