Need help with Pivoting rows to columns

Hi,
I need help with pivoting rows to columns. I know there are other posts regarding this, but my requirement is more complex and harder. So, please give me a solution for this.
There are two tables say Table 1 and Table 2.
Table1
name address email identifier
x e g 1
f s d 2
h e n 3
k l b 4
Table2
identifier TRno zno bzid
1 T11 z11 b11
1 T12 z12 b12
1 T13 z13 b13
2 T21 z21 b21
2 T22 z22 b22
As you can see the identifier is the column that we use to map the two tables. The output should be like below
output
name address email identifier TRno1 zno1 bzid1 TRno2 zno2 bzid2 TRno3 zno3 bzid3
x e g 1 T11 z11 b11 T12 z12 b12 T13 z13 b13
f s d 2 T21 z21 b21 t22 z22 b22
Also we do not know exactly how many TRno's, zno's, etc each value in the identifier will have. There may be only 1 TRNO, zno and bzid, or there may be four.
All the values must be in separate columns, and not be just comma delimitted. There are also other conditions that i have to add to restrict the data.
So, can you please tell me what is should use to get the data in the required format? We are using Oracle 10g. Please let me know if u need any more information

Something like this ?
SCOTT@orcl> ed
Wrote file afiedt.buf
  1  select a.name,
  2  a.address,
  3  a.email,
  4  b.* from (
  5  select distinct identifier
  6  ,max(trno1) trno1
  7  ,max(zno1) zno1
  8  ,max(bzid1) bzid1
  9  ,max(trno2) trno2
10  ,max(zno2) zno2
11  ,max(bzid2) bzid2
12  ,max(trno3) trno3
13  ,max(zno3) zno3
14  ,max(bzid3) bzid3
15  ,max(trno4) trno4
16  ,max(zno4) zno4
17  ,max(bzid4) bzid4
18  from (select identifier
19  ,decode(rn,1,trno,null) trno1
20  ,decode(rn,1,zno,null) zno1
21  ,decode(rn,1,bzid,null) bzid1
22  ,decode(rn,2,trno,null) trno2
23  ,decode(rn,2,zno,null) zno2
24  ,decode(rn,2,bzid,null) bzid2
25  ,decode(rn,3,trno,null) trno3
26  ,decode(rn,3,zno,null) zno3
27  ,decode(rn,3,bzid,null) bzid3
28  ,decode(rn,4,trno,null) trno4
29  ,decode(rn,4,zno,null) zno4
30  ,decode(rn,4,bzid,null) bzid4
31  from (select identifier,
32  trno,bzid,zno,
33  dense_rank() over(partition by identifier order by trno,rownum) rn
34  from table2)
35  order by identifier)
36  group by identifier) b,table1 a
37* where a.identifier=b.identifier
SCOTT@orcl> /
NAME       ADDRESS    EMAIL      IDENTIFIER TRNO1      ZNO1       BZID1      TRNO2      ZNO2       BZID2      TRNO3      ZNO3       BZID3      TRNO4      ZNO4       BZID4
x          e          g          1          T11        z11        b11        T12        z12        b12        T13        z13        b13
f          s          d          2          T21        z21        b21        T22        z22        b22
SCOTT@orcl> select * from table1;
NAME       ADDRESS    EMAIL      IDENTIFIER
x          e          g          1
f          s          d          2
h          e          n          3
k          l          b          4
SCOTT@orcl> select * from table2;
IDENTIFIER TRNO       ZNO        BZID
1          T11        z11        b11
1          T12        z12        b12
1          T13        z13        b13
2          T21        z21        b21
2          T22        z22        b22
SCOTT@orcl>Regards
Girish Sharma

Similar Messages

  • Need help in displaying Rows to Columns

    Hi,
    I am facing problem in displaying Rows to Columns
    I am using pivot function:
    select *
    from
    (select vendor_name
    from tablea)
    pivot
    (count(vendor_name)
    for vendor_name in ('a,b,'c'));
    its working fine showing vendor_name and count
    but when i want to display the output as:(How to include the Salalry column in the query?)
    Name:{a b c}
    Sal Total:(400,600,800}
    Any help will be needful for me

    Not sure what you mean:
    select  *
      from  (select deptno,sal from emp)
      pivot(sum(sal) for deptno in (10,20,30))
            10         20         30
          8750      10875       9400
    SQL> SY.

  • Need help with inserting rows in ResultSet and JTable

    hello Guru!
    i have inserted a row in my result set and i want that my table shows this row promptly after i have inserted it in my result set...
    but when i use following code for my resultset:
    rs.moveToInsertRow();
    rs.updateInt(1,nr);
    rs.updateString(2, name);
    rs.insertRow();
    Record are inserted in resultset and database but not shown in my JTable??
    Anyone a Clue to without reexecuting the query how can i display inserted row in JTable
    http://download-west.oracle.com/docs/cd/A87860_01/doc/java.817/a83724/resltse7.h
    I have refrered the following links but still clue less help Guruuuuuuu
    i m really in trobble??????

    i am just near by the Solution using the Database Metadata
    by couldn't get the ideaaaa
    ==================================================
    http://download-west.oracle.com/docs/cd/A87860_01/doc/java.817/a83724/resltse7.htm
    Seeing Database Changes Made Internally and Externally
    This section discusses the ability of a result set to see the following:
    its own changes (DELETE, UPDATE, or INSERT operations within the result set), referred to as internal changes
    changes made from elsewhere (either from your own transaction outside the result set, or from other committed transactions), referred to as external changes
    Near the end of the section is a summary table.
    Note:
    External changes are referred to as "other's changes" in the Sun Microsystems JDBC 2.0 specification.
    Seeing Internal Changes
    The ability of an updatable result set to see its own changes depends on both the result set type and the kind of change (UPDATE, DELETE, or INSERT). This is discussed at various points throughout the "Updating Result Sets" section beginning on , and is summarized as follows:
    Internal DELETE operations are visible for scrollable result sets (scroll-sensitive or scroll-insensitive), but are not visible for forward-only result sets.
    After you delete a row in a scrollable result set, the preceding row becomes the new current row, and subsequent row numbers are updated accordingly.
    Internal UPDATE operations are always visible, regardless of the result set type (forward-only, scroll-sensitive, or scroll-insensitive).
    Internal INSERT operations are never visible, regardless of the result set type (neither forward-only, scroll-sensitive, nor scroll-insensitive).
    An internal change being "visible" essentially means that a subsequent getXXX() call will see the data changed by a preceding updateXXX() call on the same data item.
    JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
    boolean ownDeletesAreVisible(int) throws SQLException
    boolean ownUpdatesAreVisible(int) throws SQLException
    boolean ownInsertsAreVisible(int) throws SQLException
    Note:
    When you make an internal change that causes a trigger to execute, the trigger changes are effectively external changes. However, if the trigger affects data in the row you are updating, you will see those changes for any scrollable/updatable result set, because an implicit row refetch occurs after the update.
    Seeing External Changes
    Only a scroll-sensitive result set can see external changes to the underlying database, and it can only see the changes from external UPDATE operations. Changes from external DELETE or INSERT operations are never visible.
    Note:
    Any discussion of seeing changes from outside the enclosing transaction presumes the transaction itself has an isolation level setting that allows the changes to be visible.
    For implementation details of scroll-sensitive result sets, including exactly how and how soon external updates become visible, see "Oracle Implementation of Scroll-Sensitive Result Sets".
    JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
    boolean othersDeletesAreVisible(int) throws SQLException
    boolean othersUpdatesAreVisible(int) throws SQLException
    boolean othersInsertsAreVisible(int) throws SQLException
    Note:
    Explicit use of the refreshRow() method, described in "Refetching Rows", is distinct from this discussion of visibility. For example, even though external updates are "invisible" to a scroll-insensitive result set, you can explicitly refetch rows in a scroll-insensitive/updatable result set and retrieve external changes that have been made. "Visibility" refers only to the fact that the scroll-insensitive/updatable result set would not see such changes automatically and implicitly.
    Visibility versus Detection of External Changes
    Regarding changes made to the underlying database by external sources, there are two similar but distinct concepts with respect to visibility of the changes from your local result set:
    visibility of changes
    detection of changes
    A change being "visible" means that when you look at a row in the result set, you can see new data values from changes made by external sources to the corresponding row in the database.
    A change being "detected", however, means that the result set is aware that this is a new value since the result set was first populated.
    With Oracle8i release 8.1.6 and higher, even when an Oracle result set sees new data (as with an external UPDATE in a scroll-sensitive result set), it has no awareness that this data has changed since the result set was populated. Such changes are not "detected".
    JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
    boolean deletesAreDetected(int) throws SQLException
    boolean updatesAreDetected(int) throws SQLException
    boolean insertsAreDetected(int) throws SQLException
    It follows, then, that result set methods specified by JDBC 2.0 to detect changes--rowDeleted(), rowUpdated(), and rowInserted()--will always return false with the 8.1.6 Oracle JDBC drivers. There is no use in calling them.
    Summary of Visibility of Internal and External Changes
    Table 12-1 summarizes the discussion in the preceding sections regarding whether a result set object in the Oracle JDBC implementation can see changes made internally through the result set itself, and changes made externally to the underlying database from elsewhere in your transaction or from other committed transactions.
    Table 12-1 Visibility of Internal and External Changes for Oracle JDBC
    Result Set Type Can See Internal DELETE? Can See Internal UPDATE? Can See Internal INSERT? Can See External DELETE? Can See External UPDATE? Can See External INSERT?
    forward-only
    no
    yes
    no
    no
    no
    no
    scroll-sensitive
    yes
    yes
    no
    no
    yes
    no
    scroll-insensitive
    yes
    yes
    no
    no
    no
    no
    For implementation details of scroll-sensitive result sets, including exactly how and how soon external updates become visible, see "Oracle Implementation of Scroll-Sensitive Result Sets".
    Notes:
    Remember that explicit use of the refreshRow() method, described in "Refetching Rows", is distinct from the concept of "visibility" of external changes. This is discussed in "Seeing External Changes".
    Remember that even when external changes are "visible", as with UPDATE operations underlying a scroll-sensitive result set, they are not "detected". The result set rowDeleted(), rowUpdated(), and rowInserted() methods always return false. This is further discussed in "Visibility versus Detection of External Changes".
    Oracle Implementation of Scroll-Sensitive Result Sets
    The Oracle implementation of scroll-sensitive result sets involves the concept of a window, with a window size that is based on the fetch size. The window size affects how often rows are updated in the result set.
    Once you establish a current row by moving to a specified row (as described in "Positioning in a Scrollable Result Set"), the window consists of the N rows in the result set starting with that row, where N is the fetch size being used by the result set (see "Fetch Size"). Note that there is no current row, and therefore no window, when a result set is first created. The default position is before the first row, which is not a valid current row.
    As you move from row to row, the window remains unchanged as long as the current row stays within that window. However, once you move to a new current row outside the window, you redefine the window to be the N rows starting with the new current row.
    Whenever the window is redefined, the N rows in the database corresponding to the rows in the new window are automatically refetched through an implicit call to the refreshRow() method (described in "Refetching Rows"), thereby updating the data throughout the new window.
    So external updates are not instantaneously visible in a scroll-sensitive result set; they are only visible after the automatic refetches just described.
    For a sample application that demonstrates the functionality of a scroll-sensitive result set, see "Scroll-Sensitive Result Set--ResultSet5.java".
    Note:
    Because this kind of refetching is not a highly efficient or optimized methodology, there are significant performance concerns. Consider carefully before using scroll-sensitive result sets as currently implemented. There is also a significant tradeoff between sensitivity and performance. The most sensitive result set is one with a fetch size of 1, which would result in the new current row being refetched every time you move between rows. However, this would have a significant impact on the performance of your application.
    how can i implement this using
    JDBC 2.0 DatabaseMetaData objects include the following methods to verify this. Each takes a result set type as input (ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_SENSITIVE, or ResultSet.TYPE_SCROLL_INSENSITIVE).
    boolean deletesAreDetected(int) throws SQLException
    boolean updatesAreDetected(int) throws SQLException
    boolean insertsAreDetected(int) throws SQLException

  • Need help setting up rows and columns for a shop page in DW

    I sell my books and design tees on my site. I'm trying to set up a new page for a new site.
    For some reason I can't get my products in a row and column fashion.
    I have a attachment file so you can see what I actually mean. thanks to all that will give advice.

    Use a table for your product catalog.
    Nancy O.
    Alt-Web Design & Publishing
    Web | Graphics | Print | Media  Specialists
    www.alt-web.com/
    www.twitter.com/altweb
    www.alt-web.blogspot.com

  • SQL Help -- Need help with pivoting the columns to rows

    I have a requierement to split the columns into multiple rows. For example:
    EMP_DEPT
    rowid empid1 ename1 dept1 empid2 ename2 dep2 empid2 ename2      dep3 empid4 ename4 dept4
    100001 1 'SCOTT' 10 2 'DAVE' 20 3 'MILLER'     10 4 SMITH 20
    100002 1 'SCOTT' 10 2 'DAVE' 20 3 'MILLER'     20      
    Note: EMP_DEPT may not always have all the 4 employee info populated for example in row 2 only 3 employees info is there
    I need to convert it and insert into EMPLOYEE table as follows:
    EMPLOYEE
    empid ename dept
    1 SCOTT 10
    2 DAVE 20
    3 MILLER 10
    4 SMITH 20
    1 SCOTT 10
    2 DAVE 20
    3 MILLER 20
    Thanks
    Kev

    Frank Thank You for your response.
    I am on oracle 10gR2.
    Posting some sample DDL and data here as requested:
    CREATE TABLE EMP
      PK          NUMBER(10),
      EMP_NAME1   VARCHAR2(100 BYTE),
      EMP_ID1     NUMBER(10),
      EMP_NAME2   VARCHAR2(100 BYTE),
      EMP_ID2     NUMBER(10),
      DEPT_NAME1  VARCHAR2(200 BYTE),
      DEPT_ID1    NUMBER(10),
      DEPT_NAME2  VARCHAR2(200 BYTE),
      DEPT_ID2    NUMBER(10)
    CREATE TABLE EMP_DEPT
    ( PK NUMBER(10),
    ENTY_TYPE VARCHAR2(100),
    ENTY_NAME VARCHAR2(100),
    ENTY_ID NUMBER(10)
    Insert into EMP
       (PK, EMP_NAME1, EMP_ID1, EMP_NAME2, EMP_ID2, DEPT_NAME1, DEPT_ID1, DEPT_NAME2, DEPT_ID2)
    Values
       (1, 'SCOTT', 10001, 'FRANK', 10002,
        'MARKETING', 10, 'ACCOUNTING', 20);
    Insert into EMP
       (PK, EMP_NAME1, EMP_ID1, EMP_NAME2, EMP_ID2, DEPT_NAME1, DEPT_ID1)
    Values
       (2, 'SCOTT1', 10003, 'FRANK1', 10004,
        'MARKETING1', 30);
    COMMIT;
    SELECT
    FROM
    EMP;
    PK     EMP_NAME1     EMP_ID1     EMP_NAME2     EMP_ID2          DEPT_NAME1     DEPT_ID1     DEPT_NAME2     DEPT_ID2
    1     SCOTT          10001     FRANK          10002          MARKETING     10          ACCOUNTING     20
    2     SCOTT1          10003     FRANK1          10004          MARKETING1     30               My requirement is to:
    SELECT from emp and INSERT INTO EMP_DEPT so that columns are broken into rows as follows
    PK ENTY_TYPE, ENTY_NAME    ENTY_ID
    1  EMPLOYEE   SCOTT        10001
    2  EMPLOYEE   FRANK        10002
    3  DEPARTMENT MARKETING    10
    4  DEPARTMENT ACCOUNTING   20    
    5  EMPLOYEE   SCOTT1       10003
    6  EMPLOYEE   FRANK1       10004
    7  DEPARTMENT MARKETING1   30          Thanks
    Kevin
    Edited by: user10210466 on Dec 8, 2010 1:37 PM

  • Need help with query for converting columns to rows

    Hello,
    I know this is a very common question asked in the forum. I have searched regading this, i did find some threads, but i was not able to achieve what i require from the answers posted. So anybody please help me.
    I have a table which is having multiple columns as follows:
    Insert into table_1 (X,Y,Z,A,B,C,D,E,F,G,H,I) values (0,0,2,0,0,1,3,0,0,0,0,0);I want to convert the result into a two column, multiple rows i.e., I want the result as follows:
    Col1 Col2
    X      0
    Y     0
    Z      2
    A     0
    B     0
    C     1
    D     3
    E     0
    F     0
    G     0
    H     0
    I      0Please anybody help me in writing the query for this..

    Is this what you are expecting:
    SQL> WITH T AS
      2  (
      3  SELECT 0 X, 0 Y, 2 Z, 0 A, 0 B, 1 C, 3 D, 0 E, 0 F, 0 G, 0 H, 0 I FROM DUAL
      4  )
      5  SELECT  'X' col1, X col2 FROM T
      6  UNION ALL
      7  SELECT  'Y' col1, Y col2 FROM T
      8  UNION ALL
      9  SELECT  'Z' col1, Z col2 FROM T
    10  UNION ALL
    11  SELECT  'A' col1, A col2 FROM T
    12  UNION ALL
    13  SELECT  'B' col1, B col2 FROM T
    14  UNION ALL
    15  SELECT  'C' col1, C col2 FROM T
    16  UNION ALL
    17  SELECT  'D' col1, D col2 FROM T
    18  UNION ALL
    19  SELECT  'E' col1, E col2 FROM T
    20  UNION ALL
    21  SELECT  'F' col1, F col2 FROM T
    22  UNION ALL
    23  SELECT  'G' col1, G col2 FROM T
    24  UNION ALL
    25  SELECT  'H' col1, H col2 FROM T
    26  UNION ALL
    27  SELECT  'I' col1, I col2 FROM T
    28  /
    C       COL2                                                                   
    X          0                                                                   
    Y          0                                                                   
    Z          2                                                                   
    A          0                                                                   
    B          0                                                                   
    C          1                                                                   
    D          3                                                                   
    E          0                                                                   
    F          0                                                                   
    G          0                                                                   
    H          0                                                                   
    C       COL2                                                                   
    I          0                                                                   
    12 rows selected.

  • Need help with pivot operator

    Hi All,
    There is a table that has data loaded from a flat file and is in the following format
    RECTYPE     610     570     620     630     640     650     660     LOC_CODE
    x     Crawfordsville     CSC     Fort Wayne     Greenfield     LaPorte     Seymour     Vincennes     
    2010 Monthly Average     2.6     1.3     2.3     1.7     1     1     1     
    1/31/2011     1     1.4     1     2.5     4.6     1.7     3.3     
    2/28/2011     1     1     1     5     4     1     4     
    3/31/2011     1     1     2.3     3.3     5.3     3.3     3.1     
    4/30/2011     1.8     1.1     1.9     1     5.1     2.5     1.7     
    5/31/2011     1     6.7     2.3     1.1     5.6     2.1     1.4     
    6/30/2011     1.8     1.9     2.2     3     2.6     3     2.1     
    loc-code     610     8888     620     630     640     650     660     
    All are the DATA_TYPE'S=VARCHAR(20)
    I Want to change it into the following format
    date     1/31/2011     2/28/2011     3/31/2011     4/30/2011     5/31/2011     6/30/2011     loc_code     2010 monthly average
    Crawfordsville 1     1     1.8     1     1.8     610     2.6
    csc     1.4     1     1     1.1     6.7     1.9     570     1.3
    Fort Wayn      2.3     1.9     2.3     2.2     620     2.3
    Greenfield     2.5     5     3.3     1     1.1     3     630     1.7
    LaPorte     4.6     4     5.3     5.1     5.6     2.6     640     1
    Seymour     1.7     1     3.3     2.5     2.1     3     650     1
    Vincennes     3.3     4     3.1     1.7     1.4     2.1     660     1
    please need hellp.
    Thanks

    Hi,
    Sorry, I don't think there's any way to get exactly what you requested. The values you give in the PIVOT ... IN clause are exact values, not alternatives.
    You could do something like this to map all alternatives to a common value:
    WITH     got_dept_grp     AS
         SELECT     country_code, job, sal
         ,     CASE
                  WHEN  job IN ('SALESMAN', 'MANAGER') AND dept = 301 THEN 30
                  WHEN  job IN ('CLERK')               AND dept = 302 THEN 30
                                                                     ELSE dept
              END     AS dept_grp
         FROM     pivot_data
    SELECT     *
    FROM     got_dept_grp
    PIVOT     (     AVG (sal)
         FOR     (job, dept_grp)
         IN     ( ('SALESMAN', 30)
              , ('MANAGER' , 30)
              , ('CLERK'   , 30)
    ;In your sample data (and perhaps in your real data), it's about as easy to explicitly define the pivoted groups individually, like this:
    WITH     got_pivot_key     AS
         SELECT     country_code, sal
         ,     CASE
                  WHEN  job = 'SALESMAN' AND dept IN (30, 301) THEN 'd30_sls'
                  WHEN  job = 'MANAGER'  AND dept IN (30, 301) THEN 'd30_mgr'
                  WHEN  job = 'CLERK'    AND dept IN (30, 302) THEN 'd30_clrk'
              END     AS pivot_key
         FROM    pivot_data
    SELECT     *
    FROM     got_pivot_key
    PIVOT     (     AVG (sal)
         FOR     pivot_key
         IN     ( 'd30_sls'
              , 'd30_mgr'
              , 'd30_clrk'
    ;Thanks for posting the CREATE TABLE and INSERT statements; that really helps!

  • Need Help with iTunes 11.0 Column Browser - PC

    In the new version of iTunes 11.0, I can't seem to get three columns when using the column browser.  I want to see Artists, Albums, and then Songs in that order, but it won't allow me to move the Songs panel as a column.  I was able to do this with the older version of iTunes.  This is a waste of screen space since the artists and albums don't require wide columns at all.  What is up with Apple these days?

    I'm using iTunes 11.0.2 on a 21" iMac that's 2 years old. Today iTunes started playing on it's own and it's never done that to me before. I had to Force Quit iTunes twice and I restarted my computer. As soon as I restarted my computer I did not open iTunes, but within 10 minutes it not only opened itself but it started playing. This is super frustrating and I need it to stop. Can anyone help?

  • Need Help in Pivot of the Columns in Oracle 9i

    Hi,
    I have a requirement where-in i need to generate the output as below:<<under EXP1 we need to populate the SUM amounts for each category i.e. group by No and Category>>
    No Vessel EXP1 EXP2 EXP3 EXP3 .....
    1 TEST 10 -8 100 0
    2 TEST 11 0 90 -17
    And the Code I am using for the same as below:
    SELECT Vessel_Code,
               dano,          
               join(cursor(select 'SUM(DECODE(ExpenseCategory,'||''''||expensecategory||''''||',GroupAmount,NULL))'||' '||expensecategory
                           from linetypes
                           where ExpenseCategory NOT IN ('ADV','BANKCHARGES','GAIN/LOSS','NONAGENT')
                           and ExpenseCategory NOT LIKE 'REBILLABLE%'
                           and ExpenseCategory NOT LIKE 'SPECIFIED%'
                           group by expensecategory))
        FROM
        (select     a.Vessel_Code        
        ,           NVL(a.ParentDANo,a.DA_NO) as dano
        ,           b.ExpenseCategory
        ,           sum(NVL(FinalDAAMount,0)+NVL(supplmnt_amount,0)) as GroupAmount
        from  da_head a
        Cross Join LineTypes b
        Left Join   DA_Detail c
        On          a.DA_No     = c.DA_No
        and         a.Credit_Status = c.Credit_Status
        and         b.DALineTypeId = c.DA_LINETYPE_ID
        where status in ('P','G')
        and         b.ExpenseCategory NOT IN ('ADV','BANKCHARGES','GAIN/LOSS','NONAGENT')
        and         b.ExpenseCategory NOT LIKE 'REBILLABLE%'
        and         b.ExpenseCategory NOT LIKE 'SPECIFIED%'
        Group by a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO)
        ,           b.ExpenseCategory
        Union
        select      a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO) as dano
        ,           SUBSTR(b.ExpenseCategory,0,Length(b.ExpenseCategory)-1) as ExpenseCategory
        ,           sum(NVL(FinalDAAMount,0)+NVL(supplmnt_amount,0)) as GroupAmount
        from  da_head a
        Cross Join LineTypes b
        Left Join   DA_Detail c
        On          a.DA_No     = c.DA_No
        and         a.Credit_Status = c.Credit_Status
        and         b.DALineTypeId = c.DA_LINETYPE_ID
        where status in ('P','G')
        and         b.ExpenseCategory NOT IN ('ADV','BANKCHARGES','GAIN/LOSS','NONAGENT')
        and         b.ExpenseCategory LIKE 'SPECIFIED%'
        Group by a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO)
        ,           SUBSTR(b.ExpenseCategory,0,Length(b.ExpenseCategory)-1)
        Union
        select      a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO) as dano
        ,           SUBSTR(b.ExpenseCategory,0,Length(b.ExpenseCategory)-1) as ExpenseCategory
        ,           sum(NVL(FinalDAAMount,0)+NVL(supplmnt_amount,0)) as GroupAmount
        from  da_head a
        Cross Join LineTypes b
        Left Join   DA_Detail c
        On          a.DA_No     = c.DA_No
        and         a.Credit_Status = c.Credit_Status
        and         b.DALineTypeId = c.DA_LINETYPE_ID
        where status in ('P','G')
        and         b.ExpenseCategory NOT IN ('ADV','BANKCHARGES','GAIN/LOSS','NONAGENT')
        and         b.ExpenseCategory LIKE 'REBILLABLE%'
        Group by a.Vessel_Code
        ,           NVL(a.ParentDANo,a.DA_NO)
        ,           SUBSTR(b.ExpenseCategory,0,Length(b.ExpenseCategory)-1)
        GROUP BY Vessel_Code,
        dano
        order by dano;The reason why I have been using the join(cursor(.....) to get the result set as :
    SUM(DECODE(ExpenseCategory,'OWNER',GroupAmount,NULL)) OWNER,
               SUM(DECODE(ExpenseCategory,'CTM',GroupAmount,NULL)) CTM,
               SUM(DECODE(ExpenseCategory,'PORT',GroupAmount,NULL)) PORT,
               SUM(DECODE(ExpenseCategory,'REBILLABLE',GroupAmount,NULL)) REBILLABLE,
               SUM(DECODE(ExpenseCategory,'SPECIFIED',GroupAmount,NULL)) SPECIFIED,
               SUM(DECODE(ExpenseCategory,'CARGO',GroupAmount,NULL)) CARGO,
               SUM(DECODE(ExpenseCategory,'ACCTTEMP',GroupAmount,NULL)) ACCTTEMPAs we don't know the exact number of expense categories to be displayed I have used cursor excluding the expense categories I don't need.When I run the same as individual query I get the correct result but when I execute it along with the query I get error maximum cursors open exceeded...
    Please let me know how can it be achieved.
    Any suggestions are welcome.
    Thanks,
    Hemanth

    The easiest way to do this, and it could be done in a few minutes, would be to move to a currently supported version of Oracle, 11gR1 or 11gR2, where we have the PIVOT and UNPIVOT operators.
    In the desupported version you have the best choice is to hit http://asktom.oracle.com and look up the solution he published there some years ago.
    I don't have the link so you can find it as fast as I can but look under "pivot" and "crosstab."

  • Need help with inserting rows in resultset

    hello!
    i want to insert a row in my result set and i want that my table shows this row promptly after i have inserted it in my result set...
    but when i use following code for my resultset:
    rs.moveToInsertRow();
    rs.updateInt(1,nr);
    rs.updateString(2, name);
    rs.insertRow();
    and call fireTableDataChanged afterwards -> nothing happens, rows are inserted in resultset but not shown in my table??
    anyone a clue??

    rs.moveToInsertRow(); // moves cursor to the insert row
    rs.updateString(1, "AINSWORTH"); // updates the
    // first column of the insert row to be AINSWORTH
    rs.updateInt(2,35); // updates the second column to be 35
    rs.updateBoolean(3, true); // updates the third row to true
    rs.insertRow();
    rs.moveToCurrentRow();
    This is from the JAVA API. Something makes me think you might want to try doing the last method execution.
    rs.moveToCurrentRow();
    Vijay

  • Need help with merging rows

    Howdy all,
    Given the following data set...
    ID   GROUP_ID   AWESOME   MOD_DATE    LAST_NAME        FIRST_NAME
    52   98              1              2/1/2011       Kirk                    James
    60   99              1              2/2/2011       Kirk                    James
    42   45              0              1/29/2011     Kirk                    James
    100  31             1             6/24/2011      Smurf                 Papa
    200  32             1             6/23/2011      Smurf                 Papa
    300  33             0             6/22/2011      Smurf                 Papa
    400  34             0             6/21/2011     Smurf                  Papa for those with the same last_name and first_name,
    where AWEAOME=0,
    I want to overwrite their GROUP_ID with the grou_ID where AWESOME=1
    and the latest DOM_DATE.
    So for James Kirk, his group_id of 45 will be set the 99
    and for Papa Smurf, his group_ids of 33 and 34 will be set to group_id 31
    Desired result
    ID   GROUP_ID   AWESOME   MOD_DATE    LAST_NAME   FIRST_NAME
    52   98             1              2/1/2011         Kirk              James
    60   99             1              2/2/2011        Kirk              James
    42   99             0             1/29/2011       Kirk              James
    100  31            1             6/24/2011       Smurf             Papa
    200  32            1             6/23/2011      Smurf             Papa
    300  31            0             6/22/2011      Smurf             Papa
    400  31            0             6/21/2011      Smurf             Papa thanks

    Something like
    UPDATE table_name dest
       SET group_id =
        (SELECT group_id
           FROM (
            SELECT group_id,
                   mod_date,
                   first_name,
                   last_name,
                   max( mod_date ) over (partition by last_name, first_name) last_mod_date
               FROM table_name src_inner
              WHERE src_inner.awesome = 1 ) src_outer
          WHERE src_outer.last_mod_date = src_outer.mod_date
            AND src_outer.first_name = dest.first_name
            AND src_outer.last_name = dest.last_name )
    WHERE awesome = 0;should work. This assumes that there is always at least 1 row where AWESOME=1 and the name matches for every row where AWESOME=0. And it assumes there are no duplicates where the same name with AWESOME=1 have the same maximum MOD_DATE.
    Justin

  • Need help with PIVOT

    Hi All,
    i'm using the following query to get data from two different tables.
    SELECT DISTINCT t1.[b1_alt_id],
                    sd_pro_des,
                    sd_app_des,
                    T2.g6_stat_dd,
                    T2.rec_date,
                    CASE
                      WHEN sd_app_des = 'Application Accepted' THEN g6_stat_dd
                      ELSE NULL
                    END AS appl_accepted_date,
                    CASE
                      WHEN sd_app_des = 'Renewal License Accepted' THEN g6_stat_dd
                      ELSE NULL
                    END renewal_accepted_date,
                    CASE
                      WHEN sd_app_des = 'Issued' THEN g6_stat_dd
                      ELSE NULL
                    END AS Issued_date
    FROM   [b1permit] t1,
           [gprocess] t2
    WHERE  t1.serv_prov_code = t2.serv_prov_code
           AND t1.b1_per_id1 = t2.b1_per_id1
           AND t1.b1_per_id2 = t2.b1_per_id2
           AND t1.b1_per_id3 = t2.b1_per_id3
           AND t1.b1_per_group = 'Licenses'
           AND t1.b1_per_type IN ( 'Company', 'Company Adult Enterprises',
                                   'Company Adult Entertainment',
                                                         'Complaint',
                                   'Individual', 'Individual Adult Enterprises',
                                   'Legal',
                                       'Special Event Civic',
                                                         'Special Event Non Civic' )
            AND t1.b1_per_category != 'History'
           AND t1.rec_status = 'A'
           AND T2.sd_app_des IN ( 'Application Accepted', 'Issued',
                                  'Renewal License Accepted',
                                  'Accepted' )
           AND T2.sd_pro_des IN ( 'Application Submittal', 'License Status' )
           AND T1.b1_appl_status = 'Issued'
    GROUP  BY t1.[b1_alt_id],
              t1.[b1_appl_status],
              t1.[b1_module_name],
              t2.sd_stp_num,
              T2.sd_pro_des,
              T2.sd_bureau_code,
              T2.sd_app_des,
              T2.g6_app_dd,
              T2.g6_stat_dd,
              T2.g6_asgn_dd,
              T2.rec_date
    ORDER  BY t1.b1_alt_id  And i'm having the following out put.
    b1_alt_id     sd_pro_des     sd_app_des     g6_stat_dd     rec_date     appli_accepted_date     renewal_accepted_date     issued_date
    LAC-000004     Application Submittal     Application Accepted     2/1/12 12:00 AM     2/1/12 9:22 AM     2/1/12 12:00 AM     NULL     NULL
    LAC-000004     License Status     Issued     2/2/12 12:00 AM     2/2/12 8:18 AM     NULL     NULL     2/2/12 12:00 AM
    LAC-000005     Application Submittal     Renewal License Accepted     1/24/12 12:00 AM     1/24/12 5:52 PM     NULL     1/24/12 12:00 AM     NULL
    LAC-000005     License Status     Issued     2/15/12 12:00 AM     2/15/12 10:03 AM     NULL     NULL     2/15/12 12:00 AMBut what i'm expecting is
    b1_alt_id     Application Accepted     Renewal License Accepted     Issued
    LAC-000004     2/1/12 12:00 AM          2/2/12 12:00 AM
    LAC-000005          1/24/12 12:00 AM     2/15/12 12:00 AMCan anyone please advice me what i should do?
    Thanks

    Hi,
    thinkingeye wrote:
    Can anyone please advice me what i should do?Sure. Post CREATE TABLE and INSERT statements for ypur sample data, and the results you want from that data (if not what you've already posted).
    Always say which version of Oracle you're using. If you're not using Oracle (the square brackets, as in "SELECT DISTINCT t1.[b1_alt_id]", make me wonder), then explain what you are using, and why you're posting the question on an Oracle forum.
    See the forum FAQ {message:id=9360002}
    The forum FAQ also has a section on pivoting: {message:id=9360005} Use one of the techniques from there.
    Post your best attempt, and point out where it is producing the wrong output. If you're getting an error message, post the complete error message.

  • 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.

  • Need help with writing a query with dynamic FROM clause

    Hi Folks,
    I need help with an query that should generate the "FROM" clause dynamically.
    My main query is as follows
    select DT_SKEY, count(*)
    from *???*
    where DT_SKEY between 20110601 and 20110719
    group by DT_SKEY
    having count(*) = 0
    order by 1; The "from" clause of the above query should be generated as below
    select 'Schema_Name'||'.'||TABLE_NAME
    from dba_tables
    where OWNER = 'Schema_Name'Simply sticking the later query in the first query does not work.
    Any pointers will be appreciated.
    Thanks
    rogers42

    Hi,
    rogers42 wrote:
    Hi Folks,
    I need help with an query that should generate the "FROM" clause dynamically.
    My main query is as follows
    select DT_SKEY, count(*)
    from *???*
    where DT_SKEY between 20110601 and 20110719
    group by DT_SKEY
    having count(*) = 0
    order by 1; The "from" clause of the above query should be generated as below
    select 'Schema_Name'||'.'||TABLE_NAME
    from dba_tables
    where OWNER = 'Schema_Name'
    Remember that anything inside quotes is case-sensitive. Is the owner really "Schema_Name" with a capital S and a capital N, and 8 lower-case letters?
    Simply sticking the later query in the first query does not work.Right; the table name must be given when you compile the query. It's not an expression that you can generate in the query itself.
    Any pointers will be appreciated.In SQL*Plus, you can do something like the query bleow.
    Say you want to count the rows in scott.emp, but you're not certain that the name is emp; it could be emp_2011 or emp_august, or anything else that starts with e. (And the name could change every day, so you can't just look it up now and hard-code it in a query that you want to run in the future.)
    Typically, how dynamic SQL works is that some code (such as a preliminary query) gets some of the information you need to write the query first, and you use that information in a SQL statement that is compiled and run after that. For example:
    -- Preliminary Query:
    COLUMN     my_table_name_col     NEW_VALUE my_table_name
    SELECT     table_name     AS my_table_name_col
    FROM     all_tables
    WHERE     owner          = 'SCOTT'
    AND     table_name     LIKE 'E%';
    -- Main Query:
    SELECT     COUNT (*)     AS cnt
    FROM     scott.&my_table_name
    ;This assumes that the preliminary query will find exactly one row; that is, it assumes that SCOTT has exactly one table whose name starts with E. Could you have 0 tables in the schema, or more than 1? If so, what results would you want? Give a concrete example, preferably suing commonly available tables (like those in the SCOTT schema) so that the poepl who want to help you can re-create the problem and test their ideas.
    Edited by: Frank Kulash on Aug 11, 2011 2:30 PM

  • 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.

Maybe you are looking for

  • Why can't I have the same apple ID for iCloud and iTunes?

    After down loading the latest upgrade on my 5s, the iCloud Apple ID (which is an email address I don't use) keeps asking me for a password that I don't have.  When I change it to a new password (I've done it 4 times) it keeps going back to the passwo

  • Retrieving imported AVCHD files from Final Cut Pro X

    Hi there, does anyone know how to retrieve raw AVCHD clips from Final Cut Pro X, after they have been imported? I shot some footage on my GH2 and it DID import from the camera into FCP X, but it's not running smooth at all. I heard that it's better t

  • What do I have to do to get WebHelp browser styles to match RH's style sheet?

    What do I have to do to get WebHelp browser styles to match RH's style sheet? In the PDF rendering, the styles conform to the .css styles, but the generated WebHelp in the browsers (Firefox and IE) does not. I've check all the generated project's top

  • Panasonic BDT130 blu-ray and wireless

    Having just purchased this how can I connect it to my wireless infinity router. The router is upstairs and the blu-Ray player and panasonic smart tv both downstairs.

  • Cash Managemnt Topics...,

    Hi All, Can any one explain how to do the below cash management related topics practically Bank and cash accounting Bank account creation and maintenance Loan account treatment Cash Forecasting Post Dated cheque treatment Bank Reconciliation Reconcil