sqloracle-databaseoracle11g

Oracle Table transpose


Below is my table

CREATE TABLE "TABLE1" 
   (    "REG" VARCHAR2(20 BYTE), 
    "SB" VARCHAR2(20 BYTE), 
    "VKYC" VARCHAR2(20 BYTE)
   ) ;

Insert into TABLE1 (REG,SB,VKYC) values ('1','2','3');
Insert into TABLE1 (REG,SB,VKYC) values ('1A','3','6');
Insert into TABLE1 (REG,SB,VKYC) values ('2','4','7');
Insert into TABLE1 (REG,SB,VKYC) values ('3','5','8');
Insert into TABLE1 (REG,SB,VKYC) values ('4','6','9');
Insert into TABLE1 (REG,SB,VKYC) values ('5','7','0');

I want result like transpose:

Reg 1 1A 2 3 4 5
Sb 2 3 4 5 6 7
Vkyc 3 6 7 8 9 0

Solution

  • This is better done in whatever third-party language (Java, C#, PHP, Python, etc.) you are using to connect to the database as transposing data is something for displaying data and is not easy when querying data.


    However, if you have a fixed number of rows that you want to output as columns then you can UNPIVOT and PIVOT to transpose:

    SELECT *
    FROM   ( SELECT reg, sb, vkyc,
                    ROW_NUMBER() OVER (ORDER BY ROWNUM) AS rn
             FROM   table1 )
           UNPIVOT(value FOR type IN (reg, sb, vkyc))
           PIVOT(MAX(value) FOR rn IN (1, 2, 3, 4, 5, 6));
    

    Which, for the sample data, outputs:

    TYPE 1 2 3 4 5 6
    REG 1 1A 2 3 4 5
    SB 2 3 4 5 6 7
    VKYC 3 6 7 8 9 0

    fiddle