Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Dynamic SQL Pivoting(Converting Row to Columns)

813401Dec 3 2010 — edited Dec 3 2010
Hi All,

I am using Oracle 9i (Oracle9i Enterprise Edition Release 9.2.0.1.0 - Production)
and also 10g version

I am facing difficulties to find out the logic for
converting the set of values in one of the columns into the column headings for the entire query.




create TABLE my_tab ( deptno VARCHAR2(5), job VARCHAR2(50), sal NUMBER);

/


insert into my_tab ( deptno,JOB, sal) values ( 10, 'ANALYST', 23000);

insert into my_tab ( deptno,JOB, sal) values ( 10, 'SALESMAN', 1500);

insert into my_tab ( deptno,JOB, sal) values ( 10, 'CLERK', 3550);

insert into my_tab ( deptno,JOB, sal) values ( 20, 'SALESMAN', 700);

insert into my_tab ( deptno,JOB, sal) values ( 20, 'ANALYST', 4200);

insert into my_tab ( deptno,JOB, sal) values ( 30, 'SALESMAN', 5600);

insert into my_tab ( deptno,JOB, sal) values ( 30, 'CLERK', 12000);

insert into my_tab ( deptno,JOB, sal) values ( 30, 'ANALYST', 19000);

/

COMMIT;

/


SELECT * FROM my_tab

/

DEPTNO ______ JOB ________ SAL

10 ______ ANALYST ________ 23000

10 ______ SALESMAN ________ 1500

10 _______ CLERK ________ 3550

20 _______ SALESMAN ________ 700

20 _______ ANALYST ________ 4200

30 _______ SALESMAN ________ 5600

30 _______ CLERK _______ 12000

30 _______ ANALYST _______ 19000



--And I wish to convert it into this structure:


DEPTNO ________ ANALYST ________ SALESMAN _________ CLERK

10 ________ 23000 ________ 1500 _________ 3550

20 ________ 4200 ________ 700 _________ NULL

30 ________ 19000 ________ 5600 _________ 12000



It may be dynamic. i.e Later i inserted more two records into My_tab.

insert into my_tab ( deptno,JOB, sal) values ( 20, 'CLERK', 3400);

insert into my_tab ( deptno,JOB, sal) values ( 30, 'MANAGER', 48000);


So it should be dynamic.
output is like this.


DEPTNO ________ ANALYST ______ SALESMAN ______ CLERK ______ MANAMGER

10 ________ 23000 ______ 1500 ______ 3550 ______ NULL

20 ________ 4200 ______ 700 ______ 3400 ______ NULL

30 ________ 19000 ______ 5600 ______ 12000 ______ 48000



Please help me regarding this.





With warm regards,
Prasanta
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 31 2010
Added on Dec 3 2010
2 comments
3,286 views