Converting Rows into Column in Oracle 10g

Hi All,                    
I m using Oracle Version 10.1.0.2.0 - Production                    
I have requirement to convert rows into column wise as per the following:                    
My Query is:                    
WITH t                    
AS ( SELECT 'A' AS x, 100 AS y FROM DUAL                     
UNION ALL                    
SELECT 'B',200 FROM DUAL                    
SELECT X, Y                    
FROM t;     
X Y
A 100
B 200
My Requirement is
A B
100 200
So any one could help me that how I resolve this.
Regards,
Prasanta

Dear frank,
Thanks for your support,.
It's working fine for static cases.If the first column is dynamic then how come i will resolve it.
Example:
Create table mytab (ID_C Varchar2(15),Value_N Number);
Records Population into MyTab table is dynamic.
Insert into mytab values('HO',5000);
Insert Into mytab values('PG1',2400);
Insert Into mytab values('PG2',3000);
Insert Into mytab values('PG3',800);
Commit;
SQL> Select * From MyTab;
IDC_ ValueN_
HO 5000
PG1 2400
PG2 3000
PG3 800
Then My expected result will be as follows
HO PG1 PG2 PG3
5000 2400 3000 800
Thanks and Regards,
Prasanta

Similar Messages

  • Pivoting rows into columns in Oracle 10g

    Hi,
    I want to pivot rows into column in some optimal way.
    I don't want to go with the DECODE option as the number of columns can be more than 200.
    i have also tried the transpose logic which is making the pl/sql block too huge.
    can i directly query the database for the desired output instead of storing the data into some arrays and displaying rows as columns?

    Hi,
    Here's a dynamic way to do this is Oracle 10, using theSQL*Plus @ command to handle the dynamic parts.
    First, let's see how we would do this using a static query:
    WITH     col_cntr    AS
         SELECT     column_name
         FROM     all_tab_columns
         WHERE     owner          = 'FKULASH'
         AND     table_name     = 'TEST_EMP'
         AND     column_name     NOT IN ('EMP_ID', 'TYPE_VAL')
    ,     unpivoted_data     AS
         SELECT     e.type_val
         ,     c.column_name
         ,     CASE c.column_name
                  WHEN  'X_AMT'  THEN  x_amt     -- *****  Dynamic section 1  *****
                  WHEN  'Y_AMT'  THEN  y_amt     -- *****  Dynamic section 1  *****
                  WHEN  'Z_AMT'  THEN  z_amt     -- *****  Dynamic section 1  *****
              END     AS v
         FROM          test_emp  e
         CROSS JOIN     col_cntr  c
    SELECT       column_name     AS type_val
    ,       SUM (CASE WHEN type_val = 'Q1' THEN v ELSE 0 END)     AS q1     -- ***** Dynamic section 2  *****
    ,       SUM (CASE WHEN type_val = 'Q2' THEN v ELSE 0 END)     AS q2     -- ***** Dynamic section 2  *****
    ,       SUM (CASE WHEN type_val = 'Q3' THEN v ELSE 0 END)     AS q3     -- ***** Dynamic section 2  *****
    ,       SUM (CASE WHEN type_val = 'Q4' THEN v ELSE 0 END)     AS q4     -- ***** Dynamic section 2  *****
    FROM       unpivoted_data
    GROUP BY  column_name
    ORDER BY  column_name
    ;Column names are hard-coded in two places:
    (1) in the sub-query unpivoted_data, we had to know that there were 3 columns to be unpivoted, and that they were called x_amt, y_amt and z_amt. You want to derive all of that from all_tab_columns.
    (2) in the main query, we had to know that there would be 4 pivoted columns in the rsult set, and that they would be called q1, q2, q3 and q4. You want to derive all that from the data actually in test_emp.
    Instead of hard-coding those 2 dynamic sections, have Preliminary Queries write them for you, a split second before you run the main query, by running this script:
    --  Before writing sub-scripts, turn off features designed for human readers
    SET     FEEDBACK    OFF
    SET     PAGESIZE    0
    PROMPT *****  Preliminary Query 1  *****
    SPOOL     c:\temp\sub_script_1.sql
    SELECT    '              WHEN  '''
    ||       column_name
    ||       '''  THEN  '
    ||       LOWER (column_name)     AS txt
    FROM       all_tab_columns
    WHERE       owner          = 'FKULASH'
    AND       table_name     = 'TEST_EMP'
    AND       column_name     NOT IN ('EMP_ID', 'TYPE_VAL')
    ORDER BY  column_name
    SPOOL     OFF
    PROMPT     *****  Preliminary Query 2  *****
    SPOOL     c:\temp\sub_script_2.sql
    SELECT DISTINCT  ',       SUM (CASE WHEN type_val = '''
    ||                type_val
    ||           ''' THEN v ELSE 0 END)     AS '
    ||           LOWER (type_val)          AS txt
    FROM           test_emp
    ORDER BY      txt
    SPOOL     OFF
    --  After writing sub-scripts, turn on features designed for human readers
    SET     FEEDBACK    5
    SET     PAGESIZE    50
    -- Main Query:
    WITH     col_cntr    AS
         SELECT     column_name
         FROM     all_tab_columns
         WHERE     owner          = 'FKULASH'
         AND     table_name     = 'TEST_EMP'
         AND     column_name     NOT IN ('EMP_ID', 'TYPE_VAL')
    ,     unpivoted_data     AS
         SELECT     e.type_val
         ,     c.column_name
         ,     CASE c.column_name
                  @c:\temp\sub_script_1
              END     AS v
         FROM          test_emp  e
         CROSS JOIN     col_cntr  c
    SELECT       column_name     AS type_val
    @c:\temp\sub_script_2
    FROM       unpivoted_data
    GROUP BY  column_name
    ORDER BY  column_name
    ;As you can see, the main query looks exactly like the static query, except that the two dynamic sections have been replaced by sub-scripts. These 2 sub-scripts are written by 2 prelimiary queries, right before the main query.
    As others have said, the fact that you're asking this question hints at a poor table design. Perhaps the table should be permanently stored in a form pretty much like unpivoted_data, above. When you need to display it with columns x_amt, y_amt, ..., then pivot it, using GROUP BY type_col. When you need to display it with columns q1, q2, ..., then pivot it using GROUP BY column_name.

  • Convert rows into columns nad vice versa in 10g

    how to convert rows into columns in 10g??

    Qwerty wrote:
    see below for rows to column case
    SQL> WITH t as
    2      (
    3       SELECT 'US' test_string FROM DUAL UNION
    4       SELECT 'AMERICA'  FROM DUAL UNION
    5       SELECT'HOLLYWOOD'  FROM DUAL UNION
    6       SELECT 'WASHINGTON'  FROM DUAL
    7      )
    8      select ltrim (sys_connect_by_path(test_string,','),',') test_string
    9        from (
    10     SELECT row_number() over(order by test_string) rno, test_string
    11       FROM t)
    12       WHERE connect_by_isleaf = 1 and rownum=1
    13       connect by rno = prior rno+1;
    TEST_STRING
    AMERICA,HOLLYWOOD,US,WASHINGTONI hope you can do it for column to rows now.That's not really rows to columns. That's rows to a column, which is more commonly called string aggregation.
    Rows to columns (or pivot) is more like:
    SQL> ed
    Wrote file afiedt.buf
      1  WITH t as
      2       (
      3        SELECT 'US' test_string FROM DUAL UNION
      4        SELECT 'AMERICA'  FROM DUAL UNION
      5        SELECT'HOLLYWOOD'  FROM DUAL UNION
      6        SELECT 'WASHINGTON'  FROM DUAL
      7       )
      8  --
      9  select max(decode(rn,1,test_string)) as col_1
    10        ,max(decode(rn,2,test_string)) as col_2
    11        ,max(decode(rn,3,test_string)) as col_3
    12        ,max(decode(rn,4,test_string)) as col_4
    13* from (select test_string, row_number() over (order by test_string) as rn from t)
    SQL> /
    COL_1      COL_2      COL_3      COL_4
    AMERICA    HOLLYWOOD  US         WASHINGTON
    SQL>And columns to rows (or unpivot) is like:
    SQL> ed
    Wrote file afiedt.buf
      1  WITH t as
      2       (
      3        SELECT 'US' col_1, 'AMERICA' col_2, 'HOLLYWOOD' col_3, 'WASHINGTON' col_4 FROM DUAL
      4       )
      5  --
      6  select col_1 as col from t union all
      7  select col_2 from t union all
      8  select col_3 from t union all
      9* select col_4 from t
    SQL> /
    COL
    US
    AMERICA
    HOLLYWOOD
    WASHINGTONor...
    SQL> ed
    Wrote file afiedt.buf
      1  WITH t as
      2       (
      3        SELECT 'US' col_1, 'AMERICA' col_2, 'HOLLYWOOD' col_3, 'WASHINGTON' col_4 FROM DUAL
      4       )
      5  --
      6  select decode(rownum,1,col_1,2,col_2,3,col_3,4,col_4) as col
      7* from t, (select * from dual connect by rownum <= 4)
    SQL> /
    COL
    US
    AMERICA
    HOLLYWOOD
    WASHINGTON
    SQL>

  • How to convert row into column

    Hi All,
    My oracle apps version is r12 and db is 10 and i am using Bi publisher version 10g.
    Is it possible to convert row into column in Rtf template,
    My Query is
    SELECT distinct pvs.vendor_site_code,sum(aia.invoice_amount)
    FROM ap_invoices_all aia, po_vendors po, po_vendor_sites_all pvs
    WHERE aia.org_id = pvs.org_id
    AND aia.vendor_id = po.vendor_id
    AND aia.vendor_site_id = pvs.vendor_site_id
    AND aia.org_id=204
    group by pvs.vendor_site_code
    And output is like this
    Vendor sitecode Invoiceamt
    EAM-ERS 79240
    STAR GATE - PAY 3245902.31
    UPS - HQ 10792040.9
    Like this
    So in template i need the output like this
    Vendor sitecode EAM-ERS STAR GATE - PAY UPS - HQ
    Invoiceamt 79240 3245902.31 10792040.9
    I tried to achieve the output using sql query but by hardcoding only i have achieved it, so i have tried to convert directly in RTF template.
    can any one tell me is it possible.
    And if new project is added from the front end ie(now the query will produce 4 rows but now in template i have created only three columns)
    Is it possible to add a new column dynamically.
    Can any one please guide me and tell me is there any example.
    Thanks & regards
    Srikkanth

    Take a look at this post: http://blogs.oracle.com/roller-ui/bsc/spider.jsp?entry=MT%3aENTRY%3a5001
    Thanks,
    Bipuser

  • How to convert rows into columns with decode function

    Hi,
    How to convert rows into columns with the help of decode function in oracle.
    thanks and regards
    P Prakash

    say
    col1 col2
    1 10
    2 20
    3 30
    then use
    select col1,
    sum(decode(col2,10,10)) "new1"
    sum(decode(col2,20,20))"new2"
    sum(decode(col2,30,30))"new3"
    from table_name
    group by col1;
    we used sum u can use ny function if wont u have to give the column name i.e col2 name also
    so i think u got it nw
    regards

  • How to convert rows into column

    Hi,
    can any one help me how to convert rows into column by pl/sql procedure.
    Thanks and Regards

    http://www.oracle.com/technology/oramag/code/tips2004/050304.html
    -- dropping the sample table if exists
    drop table rowstocol
    -- create sample table
    create table rowstocol ( name varchar2(20));
    -- Inserting rows into sample table
    insert into rowstocol values('Amit Zhankar');
    insert into rowstocol values('Piyu Yawalkar');
    insert into rowstocol values('Piyu Yawalkar');
    insert into rowstocol values('Ashish Ghelani');
    insert into rowstocol values('Aditi Zhankar');
    insert into rowstocol values('Tom Kyte');
    insert into rowstocol values('Oracle');
    -- Following query should be run to create a sql. This result sql should be run to convert rows to column.
    -- The following query uses just the tablename (whose data is to be converted) and name of the column (which is to be converted).
    -- Example taken here is table rowstocol, column name.
    SELECT cc
    FROM (select decode(rn ,1 ,'Select ',null) ||' MAX (CASE WHEN dr = '|| rownum||' THEN DECODE (rn,1, col1) END) '||
    decode(rn,maxr,' col1 from ','||'||chr(39)||','||chr(39)||'|| ') cc,rn,maxr
    from (SELECT ROWNUM rn,count(0) over() maxr FROM rowstocol) order by rn) trows
    union all
    select '(SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn' cc from dual;
    -- The result of this query will do the reqd conversion from row to column.
    -- Replace table rowstocol by your table, column name by your column.
    CC
    Select MAX (CASE WHEN dr = 1 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 2 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 3 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 4 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 5 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 6 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 7 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 8 THEN DECODE (rn,1, col1) END) col1 from
    (SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn
    Select MAX (CASE WHEN dr = 1 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 2 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 3 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 4 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 5 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 6 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 7 THEN DECODE (rn,1, col1) END) ||','||
    MAX (CASE WHEN dr = 8 THEN DECODE (rn,1, col1) END) col1 from
    (SELECT tabs.col1, DENSE_RANK () OVER (ORDER BY col1,rowid) dr,dense_rank() OVER (order by 1) rn
    FROM (SELECT NAME col1 FROM rowstocol) tabs ) group by rn;
    COL1
    Aditi Zhankar,Amit Zhankar,Ashish Ghelani,Oracle,Oracle,Piyu Yawalkar,Piyu Yawalkar,Tom Kyte
    Edited by: bhooma on Jan 20, 2009 2:44 AM

  • How to convert rows into columns

    Hi,
    How to convert rows into columns of two different tables.
    These two tables have two common columns namely (shipline,pos).
    Let me know if we have any built in functions to do this.
    thank you very much .
    Edited by: 808542 on Dec 7, 2010 8:35 PM
    Edited by: 808542 on Dec 7, 2010 8:37 PM

    Have you tried this first?
    http://forums.oracle.com/forums/search.jspa?threadID=&q=row+to+column&objID=f75&dateRange=last90days&userID=&numResults=15&rankBy=10001

  • CONVERT ROWS INTO COLUMNS IN INTERNAL TABLE

    Hi Experts,
    I want to convert rows into coloumns in final internal table.
    How to do that one. Can any one help me its very urgent.
    Regards,
    PBS.

    hi,
    Find the below code for changing rows into colums.
    data: begin of itab1 occurs 0,
    fld,
    end of itab1.
    data: begin of itab2 occurs 0,
    fld1,
    fld2,
    fld3,
    end of itab2.
    itab1-fld = 1.
    append itab1.
    itab1-fld = 2.
    append itab1.
    itab1-fld = 3.
    append itab1.
    read table itab1 index 1.
    if sy-subrc eq 0.
    itab2-fld1 = itab1-fld.
    endif.
    read table itab1 index 2.
    if sy-subrc eq 0.
    itab2-fld2 = itab1-fld.
    endif.
    read table itab1 index 3.
    if sy-subrc eq 0.
    itab2-fld3 = itab1-fld.
    endif.
    append itab2.
    loop at itab1.
    write:/ itab1.
    endloop.
    loop at itab2.
    write:/ itab2.
    endloop.
    refer the below link for further information
    internal table rows to columns
    in the final display list how can i change rows to columns and vice versa

  • Convert row into column

    I have table having below records.
    empno ename deptno
    101 a 10
    102 b 20
    103 c 10
    104 d 20
    105 e 30
    Normal Output using Group by.
    deptno count(*)
    10 2
    20 2
    30 1
    I want to display like below(rows into columns)
    Requiredl Output
    10 20 30
    2 2 1
    Deptnos are in first row and cout of deptno nos are second row.

    Check out this thread from the FAQ: {message:id=9360005}

  • Convert row into columns

    Hello World ,
    I want to make the below table data come in one row
    Name | code | MARK
    AAA | CODE2 | 50
    AAA | CODE1 | 30
    AAA | CODE3 | 22
    BBB | CODE2 | 52
    BBB | CODE3 | 53
    CCC | CODE3 | 11
    AES | CODE1 | 75
    FES | CODE2 | 44
    i want it to be like this
    NAME | CODE1 | CODE2 | CODE3
    AAA | 30 | 30 | 22
    BBB | - | 52 | 53
    CCC | - | - | 11
    is there another way of DECODE?
    Regards

    A very small amount of effort on your side would have found the FAQ thread "How do I convert rows to columns" SQL and PL/SQL FAQ

  • Convert rows to Columns in Oracle

    Hi,
    The table like
    Trx         Date
    PO121 23/11/2008
    PO122 24/11/2008
    PO123 25/11/2008
    I want to convert all the rows to columns like the below table
    PO121    23/11/2008    PO122    24/11/2008       PO123     25/11/2008
    Is it possible in Oracle ?

    Like this
    SQL> WITH T
      2  AS
      3  (
      4     SELECT 'PO121 23/11/2008' VAL FROM DUAL
      5     UNION ALL
      6     SELECT 'PO122 24/11/2008' FROM DUAL
      7     UNION ALL
      8     SELECT 'PO123 25/11/2008' FROM DUAL
      9  )
    10  SELECT MAX(DECODE(RNO,1,VAL)) VAL1, MAX(DECODE(RNO,2,VAL)) VAL2, MAX(DECODE(RNO,3,VAL)) VAL3
    11    FROM (SELECT ROW_NUMBER() OVER(ORDER BY VAL) RNO, VAL
    12       FROM T)
    13  /
    VAL1             VAL2             VAL3
    PO121 23/11/2008 PO122 24/11/2008 PO123 25/11/2008But beware the number of column must be known. without that you cant do it in a static SQL.
    Edited by: Karthick_Arp on Nov 10, 2008 1:41 AM

  • Converting Rows into Columns of a DSO

    Dear All,
    I need to create a solution to convert or transpose DSO row's INTO columns.
    For example I have Data coming from MLAN table from R3 in 3 Columns.
    In this format
    MATNR  0COUNTRY   VAT
    A             US               10
    A              IN                 20
    A              DE                30
    In Target DSO I have to convert this in multiple columns in single row.
    MATNR VAT(US )  VAT(IN)  VAT (DE)
    A            10                20      30
    I am working in BI 7.0, can any body help me with this scenerio. Please help .
    Regards.

    yes that's true ...
    But using this Txn RSANWB is it possible while loading data from R3 to DSO.
    I have never worked with Txn RSANWB so not sure is it possible to use this ..
    can u please explain it in details .. will be thankful . as i have to solve it soon
    Regards

  • Problem in Converting Database into Archivelog mode (Oracle 10G)

    Hi Team,
    I come across a strange problem in the ORACLE 10G Server.
    I am converting database mode from NoArchivelog to Archivelog mode through RMAN in 10G.
    Now When I execute these following commands through RMAN prompt it works properly as shown below?
    C:\>rman
    Recovery Manager: Release 10.2.0.1.0 - Production on Thu Nov 30 18:01:08 2006
    Copyright (c) 1982, 2005, Oracle. All rights reserved.
    RMAN> connect target /
    connected to target database: RAVI (DBID=4025722893, not open)
    RMAN> shutdown immediate;
    using target database control file instead of recovery catalog
    database dismounted
    Oracle instance shut down
    RMAN> STARTUP MOUNT;
    connected to target database (not started)
    Oracle instance started
    database mounted
    Total System Global Area 167772160 bytes
    Fixed Size 1247876 bytes
    Variable Size 79693180 bytes
    Database Buffers 79691776 bytes
    Redo Buffers 7139328 bytes
    RMAN> SQL 'ALTER DATABASE ARCHIVELOG';
    sql statement: ALTER DATABASE ARCHIVELOG
    RMAN> ALTER DATABASE OPEN;
    database opened
    RMAN>
    But this same script when i writes in the backup.ora file & pass to Rman prompt it fails,
    File backup.ora contains...
    run
    SHUTDOWN IMMEDIATE;
    STARTUP MOUNT;
    SQL 'ALTER DATABASE ARCHIVELOG';
    ALTER DATABASE OPEN;
    passed to RMAN as follows...
    C:\OracleCode\BACKUP>"C:\oracle\product\10.2.0\db_1\bin\RMAN.EXE" target /"connect target SYSTEM/sreedhar@RAVI" log="C:\ORACLE~2\LOGS\backup_log.log" append cmdfile="C:\ORACLE~2\BACKUP\backup.ora"
    RMAN> 2> 3> 4> 5> 6> 7> 8>
    then it fails giving the following errors...
    using target database control file instead of recovery catalog
    database closed
    database dismounted
    Oracle instance shut down
    RMAN-00571: ===========================================================
    RMAN-00569: =============== ERROR MESSAGE STACK FOLLOWS ===============
    RMAN-00571: ===========================================================
    RMAN-03002: failure of startup command at 11/30/2006 18:05:59
    ORA-12514: TNS:listener does not currently know of service requested in connect descriptor
    Recovery Manager complete.
    The same thing is working in the Oracle 9i but not in the Oracle 10G.
    Can Anybody plz help me in this?
    Regards,
    S.Tiwari
    .

    export ORACLE_SID=<SID>
    rman target /cmdfile="C:\ORACLE~2\BACKUP\backup.ora"
    it will connect to the default SID, there's no such thing as a default SID, what do you mean?
    But what if there are more that one SID available & I
    want to connect to SID other than the default SID.just specify the desired SID prior starting rman.
    more over the same string is working with 9i but not
    with 10G.maybe due to a bug?
    to summarize, you have two options it you would like to start up the instance:
    either you specify the SID prior starting rman and use os authentication
    or
    you register the instance statically and use oracle authentication.
    regards,
    -ap

  • CONVERTING ROWS INTO COLUMNS

    Hi,
    create table this_will_be_ugly (column1 number, column2 varchar2(2), column3 number, column4 number);
    insert into this_will_be_ugly values (1, 'MA', 100, 10000);
    insert into this_will_be_ugly values (2, 'MA', 102, 10001);
    insert into this_will_be_ugly values (3, 'MB', 100, 10001);
    insert into this_will_be_ugly values (4, 'MC', 200, 10001);
    insert into this_will_be_ugly values (5, 'MB', 220, 10003);
    insert into this_will_be_ugly values (6, 'MA', 103, 10004);
    COMMIT;
    CREATE OR REPLACE FUNCTION RET_CROSS_TAN RETURN SYS_REFCURSOR IS
    CURSOR CUR_DIST IS SELECT DISTINCT COLUMN2 FROM this_will_be_ugly;
    V_SELECT VARCHAR2(30);
    V_SELECT1 VARCHAR2(3000);
    v_final varchar2(3500);
    type ref_cur is ref cursor;
    v_ref ref_cur;
    BEGIN
    OPEN CUR_DIST;
    FETCH CUR_DIST INTO V_SELECT;
    LOOP
    IF CUR_DIST%NOTFOUND THEN
    V_SELECT1 := SUBSTR(V_SELECT1,1,LENGTH(V_SELECT1)-1);
    EXIT;
    END IF;
    V_SELECT1 := V_SELECT1||''''||V_SELECT ||''',';
    fetch cur_dist into v_select;
    END LOOP;
    CLOSE CUR_DIST;
    v_final := 'WITH PIVOT_DATA AS (select COLUMN2,COLUMN4 AS DATA,COLUMN3 from this_will_be_ugly GROUP BY COLUMN2,COLUMN3,COLUMN4)
    SELECT * FROM PIVOT_DATA PIVOT ( MIN(COLUMN3)
    FOR COLUMN2 IN ('|| V_SELECT1||'))';
    open v_ref for v_final;
    return v_ref;                                        
    END;
    I written this function to form the query which gives the pivot results.
    May i know is there any way to write the query directly instead of this function?

    Hi,
    If you want the number of columns in the output to depend on the data in the table, then you have to use dynamic SQL, more or less like you did. The number of columns in a query has to be specified when the query is compiled. You can't compile something today that figures out how many distinct values you will have, and therefore how many columns you will need, tomorrow or next month.
    See the following thread for several ways to deal with a dynamic numebr of columns
    Re: Report count and sum from many rows into many columns
    String aggregation is especially useful.

  • Convert rows into columns

    This are the 4 columns, names of this columns are defined below the table.
    01-B1 110854 800 80.02
         01-A1     110852     200     20.02
         01-A1     110852     600     60.02
         01-A1     110852     800     80.02
         01-B1     110854     200     20.02
         01-B1     110854     600     60.02
         01-B1     110854     800     80.02
         01-C1     110855     200     20.02
         01-C1     110855     600     60.02
         01-C1     110855     800     80.02
    FIRST COLUMN :MAT_NUMBER
    2> REF_NUMBER
    3>SCALE_QTY
    4>SCALE_RATE.
    NOW I WANT THE DATA SHOULD BE LIKE
    FOR EXAMPLE TAKE THE MAT_NUMBER AS '01-A1' ,AND THIS HAS THREE ROWS.
    OK.
    THEN IN MY RESULTANT QUERY SHOULD BE ABLE TO GET LIKE THIS .
    MAT_NUMBER------REF_NUMBER------SCALE_QTY------SCALE_QTY_RATE----SCALE_QTY2-----SCALE_QTY_RATE2---SCALE_QTY3----SCALE_QTY_RATE3
    01-A1------------------110852---------------200------------------20.2--------------------------600---------------60.02------------------------800-----------------------80.02     
    -SCALE_QTY2-----SCALE_QTY_RATE2---SCALE_QTY3----SCALE_QTY_RATE3 THIS COLUMNS SHOULD BE A DYNAMIC .I.E IF '01-A1' HAS 3 ROWS
    THEN IN RESULT THERE SHOULD BE A 3 NEW COLUMNS.
    THREE ROWS OF 01-A1 SHOULD BE CONVERTED TO SINGLE ROW WITH 3 NEW COLUMNS.
    MY DB VERSION :Oracle Database 10g Enterprise Edition Release 10.2.0.4.0
    MAT_NUMBER REF_NUM SCALE_QTY1 SCALE_RATE1 SCALE_QTY2 SCALE_RATE2 SCALE_QTY3 SCALE_RATE3 ---THIS ARE THE COLUMNS
    01-A1 110852 200 20.02 600 60.02 800 80.02. ---THIS IS THE THREE ROW DATA
    01-B1 110854 ---OF 01-A1
    01-C1
    PLEASE TELL ME THE QUERY ..
    I HAVE TRIED WITH DECODE AND GROUP BY
    BUT ITS VAIN
    Please help me on this...
    Im using 10g 10.4 version
    Edited by: 904032 on Jun 7, 2012 10:38 PM

    This is the basis for pivoting your data...
    SQL> ed
    Wrote file afiedt.buf
      1  with test as (select '01-B1' as mat_number, 110854 as ref_number, 800 as scale_qty, 80.02 as scale_rate from dual union all
      2                select '01-A1', 110852, 200, 20.02 from dual union all
      3                select '01-A1', 110852, 600, 60.02 from dual union all
      4                select '01-A1', 110852, 800, 80.02 from dual union all
      5                select '01-B1', 110854, 200, 20.02 from dual union all
      6                select '01-B1', 110854, 600, 60.02 from dual union all
      7                select '01-B1', 110854, 800, 80.02 from dual union all
      8                select '01-C1', 110855, 200, 20.02 from dual union all
      9                select '01-C1', 110855, 600, 60.02 from dual union all
    10                select '01-C1', 110855, 800, 80.02 from dual)
    11  --
    12  -- end of test data
    13  --
    14  select mat_number
    15        ,ref_number
    16        ,max(decode(rn,1,scale_qty)) as scale_qty1
    17        ,max(decode(rn,1,scale_rate)) as scale_rate1
    18        ,max(decode(rn,2,scale_qty)) as scale_qty2
    19        ,max(decode(rn,2,scale_rate)) as scale_rate2
    20        ,max(decode(rn,3,scale_qty)) as scale_qty3
    21        ,max(decode(rn,3,scale_rate)) as scale_rate3
    22        ,max(decode(rn,4,scale_qty)) as scale_qty4
    23        ,max(decode(rn,4,scale_rate)) as scale_rate4
    24  from (select mat_number
    25              ,ref_number
    26              ,scale_qty
    27              ,scale_rate
    28              ,row_number() over (partition by mat_number, ref_number order by 1) as rn
    29        from   test
    30       )
    31* group by mat_number, ref_number
    SQL> /
    MAT_N REF_NUMBER SCALE_QTY1 SCALE_RATE1 SCALE_QTY2 SCALE_RATE2 SCALE_QTY3 SCALE_RATE3 SCALE_QTY4 SCALE_RATE4
    01-A1     110852        800       80.02        200       20.02        600       60.02
    01-B1     110854        800       80.02        200       20.02        800       80.02        600       60.02
    01-C1     110855        600       60.02        200       20.02        800       80.02If you require a dynamic number of columns then you have a completely different issue and methods to deal with that are shown in the threads linked to by the FAQ: {message:id=9360005}

Maybe you are looking for