1

I'm having table and data like below,

Create table transpose (a number, b number, c number); 

insert into transpose values (1,4,7);
insert into transpose values (2,5,8); 
insert into transpose values (3,6,9); 
commit; 
select * from transpose; 

A B C 
1 4 7 
2 5 8 
3 6 9

Question: I need below output using sql query, Is this possbile to retrive data (Transpose data)?

   A B C 
   1 2 3 
   4 5 6 
   7 8 9

Please help to resolve this.

3
  • Your table transpose has no order. Does a transpose operation make sense without order?
    – Codo
    Sep 7, 2015 at 11:54
  • Lookup 'pivot' in the Oracle docs
    – WW.
    Sep 7, 2015 at 12:31
  • @WW. good point; I updated the solution. I assume that before pivoting, the table must be transformed in the key - value format. Sep 7, 2015 at 13:39

1 Answer 1

0

There are two important things to consider.

1) a SQL table has no implicite order, so you must add the order by information to uniquely define the columns of the transposed table. (I added a column ID in the table to simulate it).

2) If you are looking for a solution for fixed number of columns and rows, you may code the result in the SQL query see below (For a dynamic solution I'd not recommend to use SQL)

 select 
   (select a from transpose where id = 1) a,
   (select a from transpose where id = 2) b,
   (select a from transpose where id = 3) c
 from dual
 union all
 select 
   (select b from transpose where id = 1) a,
   (select b from transpose where id = 2) b,
   (select b from transpose where id = 3) c
 from dual
 union all
 select 
   (select c from transpose where id = 1) a,
   (select c from transpose where id = 2) b,
   (select c from transpose where id = 3) c
 from dual;

.

     A          B          C
 ---------- ---------- ----------
     1          2          3 
     4          5          6 
     7          8          9

UPDATE - solution with PIVOT

As proposed by @WW here solution with pivot

 with trans as (
 /* add one select for each column */
 select id, 'A' col_name, a col_value from transpose union all
 select id, 'B' col, b col_value from transpose union all
 select id, 'C' col, b col_value from transpose)
 select * from trans
 PIVOT (sum(col_value) col_value 
 for (id) in 
 (1 as "C1", /* add one entry for each row (ID) */
 2 as "C2",
 3 as "C3" )
 )
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.