Need help on Unpivot (Columns to rows conversion)

Could you please help me to do unpivot using sql?
Table creation and insertion scripts:
create table REQ
ID NUMBER,
VALUE VARCHAR2(20)
insert into REQ (ID, VALUE)
values (1, 'HI,HELLO, KARTHI');
insert into REQ (ID, VALUE)
values (2, 'ARE,YOU,FINE,BHAR');
insert into REQ (ID, VALUE)
values (3, '100,200,300');
commit;
I need to view the data in the below format
ID VALUE
1 HI
1 HELLO
1 KARTHI
2 ARE
2 YOU
2 FINE
2 BHAR
3 100
3 200
3 300

However, I would take care on the performance issue.So let's use the model clause:
SQL> set autotrace on
SQL> select id
  2       , v
  3    from req
  4   model
  5         partition by (id)
  6         dimension by (0 i)
  7         measures (value v)
  8         rules iterate (10) until (instr(v[iteration_number+1],',') = 0)
  9         ( v[iteration_number+1] = substr(v[iteration_number],instr(v[iteration_number],',')+1)
10         , v[iteration_number] = substr(v[iteration_number],1,instr(v[iteration_number],',')-1)
11         )
12   order by id
13       , i
14  /
                                    ID V
                                     1 HI
                                     1 HELLO
                                     1  KARTHI
                                     2 ARE
                                     2 YOU
                                     2 FINE
                                     2 BHAR
                                     3 100
                                     3 200
                                     3 300
10 rijen zijn geselecteerd.
Uitvoeringspan
   0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=3 Card=3 Bytes=75)
   1    0   SORT (ORDER BY) (Cost=3 Card=3 Bytes=75)
   2    1     SQL MODEL (ORDERED FAST) (Cost=3 Card=3 Bytes=75)
   3    2       TABLE ACCESS (FULL) OF 'REQ' (TABLE) (Cost=2 Card=3 By
          tes=75)
Statistics
         48  recursive calls
          0  db block gets
         11  consistent gets
          0  physical reads
          0  redo size
        528  bytes sent via SQL*Net to client
        271  bytes received via SQL*Net from client
          6  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
         10  rows processedRegards,
Rob.

Similar Messages

  • Column to row conversion using script

    Hello,
    I am in need of a script to convert a file having 1 column to rows.
    e.g
    File is having entries like below
    1
    2
    3
    4
    5
    And I want to convert them like below.
    1 2 3 4 5
    Can any body help me on this ?
    Thank you
    Regards,
    ~Anoop

    Please show what you type.
    I test my example.
    For 10st post
    #!/bash - This line must present
    For my example - attantion - first comannd printf
    You result look like you type print
    Regards.
    Edited by: Nik on 28.06.2011 11:44

  • Need help with complex column creation command

    Hello, all
    I need help with a complex column creation command and SQL anywhere help is not sufficient for it.
    Here is the situation:
    I need to write a generic DDL "alter table" command, which can add/modify columns without knowing in advance if they already exist in the destination table.
    Is there a command, which looks like:
    alter table "table1" add (on existing modify) column1 <datatype> <default> ?
    Thank you,
    Arcady

    Hi.
    I don't think this is supported in alter table command. But you can code that inside an if statement which queries systables & syscolumns. Your code should be something like that:
    if (select count(*) from sysobjects, syscolumns where sysobjects.id = syscolumns.id and sysobjects.name = 'some_table' and syscolumns.name = 'some_column') < 1
    begin
        alter table some_table add some_column numeric(12) not null
    end
    This is an example..
    Andreas.

  • CTL(control file) need help to load column data in test file  as row data

    Dear Experts,
    My data file having data like
    COMPANY1 SUPP1 SUPPTYP1 SUPPDISTANCE1...SUPP100 SUPPTYP100 SUPPDISTANCE100
    COMPANY2 SUPP1 SUPPTYP1 SUPPDISTANCE1...SUPP100 SUPPTYP100 SUPPDISTANCE100
    i am trying to load in to oralc table desc as bellow and trying to load this into row data how can i do?
    this ctl will load only for first suppliler only how can i load rest 99 supplier
    LOAD DATA
    INFILE '/data/Supplier.dat'
    INSERT
    INTO SUPPLIERDETAIL
    COMP_CD position(1:8) char(8),
    SUPPLR_ID position(9:15) char(7),
    LOC_ID position(16:20) char(5),
    SUPPLR_DIST position(21:24) char(4),
    SUPPLR_TYP position(25:) char(1)
    Many thanks
    Kalinga

    I take it that you are running the process on UNIX box based on '/data/Supplier.dat'.
    Try to –
    1. Break the records into multiple lines > Try using awk/ or perl
    COMPANY1 SUPP1 SUPPTYP1 SUPPDISTANCE1...SUPP100 SUPPTYP100 SUPPDISTANCE100
    COMPANY2 SUPP1 SUPPTYP1 SUPPDISTANCE1...SUPP100 SUPPTYP100 SUPPDISTANCE100
    Should appear in your output file as –
    COMPANY1 SUPP1 SUPPTYP1 SUPPDISTANCE1
    COMPANY1 SUPP100UPPTYP100 SUPPDISTANCE100
    COMPANY2 SUPP1 SUPPTYP1 SUPPDISTANCE1
    COMPANY2 SUPP100UPPTYP100 SUPPDISTANCE100
    2. Output from 1 -> Save it to a file
    3. Pass the output (point 2) as the Input file for the CTL to read
    Etbin’s Solution is fine but don’t forget you have for each row 100 occurrences of Supplier information – so that makes 100 INTO Table’s code to put into your CTL file.
    Shailender Mehta

  • Mother of all unpivots - columns to rows?

    I have multiple tables as follows:
    eventdate event1 event2 event3 event4 ... eventn
    1/1/07 8 5 3 2 ... 7
    2/1/07 1 14 6 9 ... 22
    n/n
    The tables have different column headers (apart from date), different numbers of columns and different numbers of rows.
    I'd like to copy the data from these tables to one table as follows:
    tablename eventname eventdate count
    table1 event1 1/1/07 8
    table1 event2 1/1/07 5
    etc
    Can anyone advise a solution? Something that handled one source table and could be set up to cycle through multiple tables via script would be great.
    I have hit google and forums hard and seen a lot of solutions that either hard code column names or parse the contents of a delimited data column. This is not what I'm after.
    Thanks in advance
    user592258

    Prior to 11g, unpivot goes like this:
    SELECT id, column_value
    FROM   your_table t1
         , TABLE(your_collection_type(col1,col2,col3,col4)) t2;which transforms
    id, col1, col2, col3, col4into
    id  column_value
    id  column_value
    id  column_value
    id  column_valueIt gets a little more complicated if you have to generate a second column to show which source column the value was taken from. You would need an object type with two attributes and a collection of that type, and then use something like
    SELECT id, t2.label, t2.val
    FROM   your_table t1
         , TABLE(your_collection_type
           ( your_object_type(1,col1)
           , your_object_type(2,col2)
           , your_object_type(3,col3)
           , your_object_type(4,col4))
           ) t2;

  • Need Help with finding Mean across rows

    Hi all,
    I have a requirement of finding mean of several columns across a row. The tricky part is there might or might not be a value in each of the rows & the average must be calculated for the ones which has a value. Let me give you an example:
    col1 col2 col2 col4
    1 NULL 3 5 --> Mean will be (1+3+5)/3 = 3
    NULL NULL 2 4 --> Mean will be (2+4)/2 = 3.
    One option (dump acc to me) is to get the whole record into a %ROWTYPE variable, parse through each of the columns, see if the value is not null & greater than 0, increment the counter (i) & calculate the sum. Finally do a sum/i. One mean has 215 columns that needs to be averaged and having a separate if-end if seems illogical. there must be a smart solution to find this kind of average. Please help.
    Thanks,
    Sirisha

    Hi, Sirisha,
    siri_me wrote:
    Hi all,
    I have a requirement of finding mean of several columns across a row. The tricky part is there might or might not be a value in each of the rows & the average must be calculated for the ones which has a value. Let me give you an example:
    col1 col2 col2 col4
    1 NULL 3 5 --> Mean will be (1+3+5)/3 = 3
    NULL NULL 2 4 --> Mean will be (2+4)/2 = 3.If you only have a few columns, you can do something like this:
    SELECT          (NVL (col1, 0)     + NVL (col2, 0)     + NVL (col3, 0)     + NVL (col4, 0)
          / NULLIF ( NVL2 (col1, 1, 0) + NVL2 (col2, 1, 0) + NVL2 (col3, 1, 0) + NVL2 (col4, 1, 0)
                      , 0
    FROM     table_x
    One option (dump acc to me) What does "dump acc to me" mean?
    is to get the whole record into a %ROWTYPE variable, parse through each of the columns, see if the value is not null & greater than 0, increment the counter (i) & calculate the sum. Finally do a sum/i. One mean has 215 columns that needs to be averaged and having a separate if-end if seems illogical. there must be a smart solution to find this kind of average. Please help.The smart way is to store the numbers in one column to begin with. The fact that it makes sense to take an average of them indicates that they are the same entity, so rather than a table like this:
    id     col1     col2     col3     col4
    10     1          3     5
    11               2     4it would make more sense to have a table like this:
    id     val     attr
    10     1     1
    10     3     3
    10     5     4
    11     2     3
    11     4     4If you are stuck with a design like the former, with col1, col2, col3 and col4 (or ... col215) then you can Unpoivot the data into a form like the latter, with only 3 columns. Then you can use the AVG function.

  • Need help with custom column in BI Publisher

    Hi Guru's
    I have started working with BI Publisher Recently and need with below issue
    Can you please let me know how can i create a custom column like % based on two existing measures in the report
    I tried creating it in obiee report and used that SQL to create BI Publisher Report , but the result column in obiee is not working as expected in BI Publisher,
    can some one please help me with this
    Thanks a lot in advance.

    This column can be calculated in BIP RTF template. But if it is a column inside a FOR-loop
    then it may need to be calculated slightly different.
    Like I said, get the xml data and rtf then send it to me : [email protected]
    and will get it fixed for you.
    thanks
    Jorge

  • Needs  help to retrive the last row in a  select query without using rownum

    Hi ,
    i need to retrive the last row from the select sub query without using rownum.
    is there any other way to retrive the last row other than the below query.
    is that the ROWNUM=1 will always retrive the 1 row of the select query ?
    select from*
    *(select ename from employee where dept_id=5 order by desc) where rownum=1;*
    Please advise.
    thanks for your help advance,
    regards,
    Senthur

    957595 wrote:
    Actually my problem is ithat while selecting the parents hiearchy of the child data using
    CONNECT BY PRIOIR query
    I need the immediate parent of my child data.
    For example my connect BY query returns
    AAA --- ROOT
    BBB --PARENT -2
    CCC --PARENT-1
    DDD IS my input child to the connect by query
    Immediate parent of my child data "DDD" ---> CCC(parent -1)
    i want the data "CCC" from the select query,for that i am taking the last row of the query with rownum.
    I got to hear that using ROWNUM to retrive the data will leads to some problem.It is a like a magic number.I am not sure what the problem will be.
    So confusing with using this rownum in my query.
    Please advice!!!It's not quite clear what you're wanting, but perhaps this may help?
    you can select the PRIOR values to get the parent details if you want...
    SQL> ed
    Wrote file afiedt.buf
      1  select empno, lpad(' ',(level-1)*2,' ')||ename as ename, prior empno as mgr
      2  from emp
      3  connect by mgr = prior empno
      4* start with mgr is null
    SQL> /
         EMPNO ENAME                                 MGR
          7839 KING
          7566   JONES                              7839
          7788     SCOTT                            7566
          7876       ADAMS                          7788
          7902     FORD                             7566
          7369       SMITH                          7902
          7698   BLAKE                              7839
          7499     ALLEN                            7698
          7521     WARD                             7698
          7654     MARTIN                           7698
          7844     TURNER                           7698
          7900     JAMES                            7698
          7782   CLARK                              7839
          7934     MILLER                           7782
    14 rows selected.(ok, not the best of examples as the mgr is already known for a row, but it demonstrates you can select prior data)

  • Need Help for Pivoting Columns in table

    I have a data like below in the table
    col1 col2 col3 col4
    a b 10 jan-11
    aa b 20 feb-11
    aab b 30 mar-11
    Need desire o/p like
    col1 col2 jan-11 feb-11 mar-11
    a b 10
    aa b 20
    aab b 30
    Can anyone help me on this? decode is not the option here because my table gets dynamic data and rows count can vary too(eg. 2000).
    Thanks,
    -KP

    Please try searching the forum BEFORE you ask a question.. There are NUMEROUS posting son the subject:
    http://forums.oracle.com/forums/search.jspa?objID=f75&q=pivot
    Thank you,
    Tony Miller
    Webster, TX
    Never Surrender Dreams!
    JMS
    If this question is answered, please mark the thread as closed and assign points where earned..

  • Need help to count number of rows and display in file

    Hello,
    my scenario is IDOC to File......i am using XSLT mapping and using FCC parameters to convert the flat file.
    now new requirement is i need to count number of rows and add count value last of the file.
    Please let me know how to do it,
    thanks in advance for your help.
    Regards,
    Chinna

    thanks again, one more Q.
    in XSLT mapping i have written for loop for complete structure.
    example : <Details>
                         <node1>
                         <node2>
                   </details>
    in XSLT mapping
                         <xsl:for-each select="ZMATMAS_01/IDOC/E1MARAM">
         <Details>
         </Details>
         </xsl:for-each>
    if i add the field at target side....then i will come under details node and it will be repeated.
    how to declare in XSLT mapping.

  • Dynamic internal table- column to row conversion

    Hello all,
    Inside a program i generate a dynamic internal table and
    This table has one single column. But I need to convert the rows as columns.
    Eg:
    dynamic internal table ITAB has content
    Forbes
    Times
    Reuters
    Warner
    stern
    I would like to have a ITAB2 like this
    Forbes Times Reuters Warner Stern
    Please note this is a Dynamic internal table!!!!
    I need some approach for my problem. Thanks a lot in advance.
    Karthik.

    Hi karthik,
    1.
      For this purpose,
      in my program,
    <b>  there is an INDEPENDENT FORM</b>
       whose inputs are
    <b>  LIST OF FIELDS, (just as u require)</b> 
    and from those, it consructs dynamic table.
    2. Here is the program.
    the dynamic table name will be
    <DYNTABLE>.
    3. U can use this program (FORM in this program)
    to generate any kind of internal table
    by specifying list of fields.
    4.
    REPORT abc.
    COMPULSORY
    FIELD-SYMBOLS: <dyntable> TYPE ANY TABLE.
    FIELD-SYMBOLS: <dynline> TYPE ANY.
    DATA: lt TYPE lvc_t_fcat.
    DATA: ls TYPE lvc_s_fcat.
    FIELD-SYMBOLS: <fld> TYPE ANY.
    DATA : fldname(50) TYPE c.
    DATA : ddfields LIKE ddfield OCCURS 0 WITH HEADER LINE.
    START-OF-SELECTION.
    field list
      ddfields-fieldname = 'BUKRS'.
      APPEND DDFIELDS.
      ddfields-fieldname = 'MATNR'.
      APPEND DDFIELDS.
      PERFORM mydyntable .
    see <DYNTABLE> in debug mode.
      BREAK-POINT.
    INDEPENDENT FORM
    FORM mydyntable .
    Create Dyn Table From FC
      FIELD-SYMBOLS: <fs_data> TYPE REF TO data.
      FIELD-SYMBOLS: <fs_1>.
      FIELD-SYMBOLS: <fs_2> TYPE ANY TABLE.
      DATA: lt_data TYPE REF TO data.
      data : lt TYPE lvc_t_fcat .
    CONSTRUCT FIELD LIST
      LOOP AT ddfields.
        ls-fieldname = ddfields-fieldname.
        APPEND ls TO lt.
      ENDLOOP.
      ASSIGN lt_data TO <fs_data>.
      CALL METHOD cl_alv_table_create=>create_dynamic_table
        EXPORTING
          it_fieldcatalog           = lt
        IMPORTING
          ep_table                  = <fs_data>
        EXCEPTIONS
          generate_subpool_dir_full = 1
          OTHERS                    = 2.
      IF sy-subrc <> 0.
      ENDIF.
    Assign Dyn Table To Field Sumbol
      ASSIGN <fs_data>->* TO <fs_1>.
      ASSIGN <fs_1> TO <fs_2>.
      ASSIGN <fs_1> TO <dyntable>.
    ENDFORM. "MYDYNTABLE
    regards,
    amit m.

  • Need help in date columns

    Hi,
    Need a help in using a date columns, I have the below 2 columns (mm/dd/yyyy hh:mi:ss) and I want to exactly find the number of hours and minutes between those 2. please help me.
    Start time - 9/2/2010 8:12:03 AM
    End time - 9/3/2010 9:12:03 AM
    Thanks

    this might help:
    with t as
       select to_date('9/2/2010 8:12:03 AM', 'mm/dd/yyyy hh:mi:ss PM') Start_Time
             ,to_date('9/3/2010 9:12:03 AM', 'mm/dd/yyyy hh:mi:ss PM') End_Time from dual
    select trunc((t.End_Time - t.Start_Time) * 24)  as Hour_difference
          ,trunc((t.End_Time - t.Start_Time) * 24 * 60)  as Min_difference from t

  • Needed help to add columns from one table to another table

    Hi,
    I have emp and dept tables. I think most of all might know what columns it's contain. Now I want to create table emp_dept with all emp and dept table columns.
    I have wrote the below query it's worked too. But I think there should be some more other queries to get accomplish the same task. Plz let me know.
    create table emp_dept as select a.*, b.dname, b.loc from emp a full outer join dept b on a.deptno = b.deptno where 1=2
    Thanks for your time..

    Hi,
    1004909 wrote:
    Hi,
    I have emp and dept tables. I think most of all might know what columns it's contain. Now I want to create table emp_dept with all emp and dept table columns.
    I have wrote the below query it's worked too. But I think there should be some more other queries to get accomplish the same task. Why do you think that?
    Plz let me know.
    create table emp_dept as select a.*, b.dname, b.loc from emp a full outer join dept b on a.deptno = b.deptno where 1=2"WHERE 1 = 2" means you want to create the table, but not put any rows in it. In that case, theere's no need for a full outer join; a simple inner join would do just as well.
    There is no single "right" or "best" table. (Most of us would have differerent jobs if there were.)
    It does, however, make sense to talk about the "right" or "best" table for some specific purpose .
    The emp and dept tables in the scott schema are great for transaction processing, where rows are frequenctly INSERTed, UPDATEd and/or DELETEd. For example, if department 10 moves from New York to Pune, you only have to find and UPDATE 1 row, and that one UPDATE will affect all employees in departemnt 10, regardess of how many there are.
    What purpose will the emp_dept table have? Why is the table design used in the scott schema not best for you?
    One possibility is that you need a tale that is very fast to query, even though it may be very inefficient for transactions. For example, you might want a data warehouse that is only refreshed once a day, and were you can run several common queries quickly, without joining the emp and dept tales.
    Another possibility is that your data model (that is, what are the entities and the attributes) is different. For example, you may have a model where employees King and Miller both work in department 10, but King's location is New York, but Miller's is Pune.
    In either of these situations, the table you posted migt be the best design. Why are you asking the question? What is the problem with the emp_dept table you posted?

  • Need help with discount column

    Hi,
    I have managed to create an invoive after discovering that I had LiveCycleDesigner included with Creative Suite 3
    I only have very basic skills in this area, so please bear with me
    I'm hoping what I am after is easy enough for someone out there to help me with.
    As you can see, I have created the below columns.
    The amount column is...     Show: calculate*    Quantity * Unit Price (with unit price being the Binding name under the Object tab)
    So what I would like to do is add the discount variable in and need to know the script to enable this.
    The Binding names are Quantity, Decgription, UnitPrice, ItemDiscount and Amount.
    I got somewhere with the amount column as...       Show: calculate*    Quantity * UnitPrice * ItemDiscount / 100
    But this left me with the actual discount in the amount column rather than the amount - discount.
    I tried a few other ideas, but couldn't seem to get it right so I thought it best to get those who know to give me the right answer.
    The other question is after I open the template with Adobe Reader, and fill it out , is it possible to save the resulting document as a 'standard' PDF?
    So far I have had to export as jpg and then convert to PDF. I'm sure I must be missing something obvious....
    I'm using windows 7 and LiveCycle Designer 8
    Thanks
    Martin

    Hi,
    Thanks for your help.
    Wasn't sure how to apply the maths to the script and get it to work:)
    They both worked perfectly
    Is it possible for the Amount field to be left blank  unless data is enetered in the other columns?
    Right now the Preview PDF has a coloum of $0.00 under amount
    As for saving the PDF
    When I go to Save As in Adober Reader I get the following message
    I've had a look through both the LiveCycle and PDF documents but have been unable to find any adjustable settings that might change this.s
    I presume the Feild Display Pattern Szzz,zz9.99 is the correct way to remove the $ signs?
    Thanks again
    Martin

  • Column to row conversion

    I would like to convert rows to columns of a sql.
    select col1, col2, col3, col4
    ABC 1 2 3
    DEF 4 5 6
    GHI 7 8 9
    I want to convert to
    ABC DEF GHI
    1 4 7
    2 5 8
    3 6 9
    Thanks for your response.

    select regexp_substr( col1,'[^\,]+',1,1) column1,
           regexp_substr( col1,'[^\,]+',1,2) column2,
           regexp_substr( col1,'[^\,]+',1,3) column3
    from (
    WITH t AS
    (select 'ABC' col1,  1 col2, 2 col3, 3 col4 from dual union
    select 'DEF', 4, 5, 6 from dual union
    select   'GHI', 7, 8, 9 from dual
    SELECT  substr(SYS_CONNECT_BY_PATH (col1, ' ,'),2) col1
    FROM (SELECT col1,
    ROW_NUMBER () OVER ( ORDER BY COl1) rn
    FROM t)
    WHERE connect_by_isleaf = 1
    START WITH rn = 1
    CONNECT BY PRIOR rn = rn - 1
    union all
    SELECT  substr(SYS_CONNECT_BY_PATH (col2, ' ,'),2) col2
    FROM (SELECT col2,
    ROW_NUMBER () OVER ( ORDER BY COl2) rn
    FROM t)
    WHERE connect_by_isleaf = 1
    START WITH rn = 1
    CONNECT BY PRIOR rn = rn - 1
    union all
    SELECT  substr(SYS_CONNECT_BY_PATH (col3, ' ,'),2) col3
    FROM (SELECT col3,
    ROW_NUMBER () OVER ( ORDER BY COl3) rn
    FROM t)
    WHERE connect_by_isleaf = 1
    START WITH rn = 1
    CONNECT BY PRIOR rn = rn - 1
    union all
    SELECT  substr(SYS_CONNECT_BY_PATH (col4, ' ,'),2) col4
    FROM (SELECT col4,
    ROW_NUMBER () OVER ( ORDER BY COl4) rn
    FROM t)
    WHERE connect_by_isleaf = 1
    START WITH rn = 1
    CONNECT BY PRIOR rn = rn - 1
    ) t1

Maybe you are looking for