SQL aggregate ( sub select )

Hi * ,
I have the following problem :
One view which contains the inventory of sales volume based on month and year ( numbers )
example :
month Year volume
1 2008 105
2 2008 107
3 2008 102
.. 2008 ..
12 2008 130
.. 2009 ..
1 2011 220
2 2011 210
9 2011 250
12 2011 270
1 2012 290
I am trying to build a query to represent the growth of sales to be used in a graph , i.e comparison between the sales of current month ( last month ) of the current year ( last year ) and the last sales of last month of last years .
would somebody be able to help ?
thanks

Thanks , but the I am not so deep in the mining techiques and i found your sql a bit difficult for me :-(
This is the sql which I used in my graph presentation , till December ot was Ok , but as of January 2012 , it will not work
select year , ROUND(sum(volume)) total_in_month froms ales
where month=12
group by year
order by year ;
this would output the following :
2007     25
2008     30
2009     59
2010     101
2011     197
it will not output the volume in January ( 1) in 2012
how would I rewrite your sql ?

Similar Messages

  • Aggregate Sub-Selects

    OK, this is probably only for the more advanced.
    I have a query that gives me an (ORA-000979) Not a Group By Expression whenever I have a sub-select in the select clause that has an aggregate function.
    For Example, the following:
    SELECT
    Items.A,
    SUM(Items.B * Items.C) As D,
    Inventory.A,
    Warehouses.A,
    (SELECT
    Sum(InventoryAudit.Qty)
    FROM
    InventoryAudit
    WHERE
    InventoryAudit.Item_ID =
    InventoryMain.Item_ID)
    FROM
    Inventory,
    Items,
    Warehouses
    WHERE
    ITEMS.A = 4
    AND Warehouses.A = Items.D
    Group By
    Items.A,
    Inventory.A,
    Warehouses.A
    null

    Braden,
    As moonriver pointed out, you are missing the InventoryMain table in your from clause in your inner sub-query.
    You also don't have enough join conditions in your outer query. You have three tables in your outermost from clause: inventory, items, and warehouses. Bearing in mind that the minimum number of join conditions required to join n tables is n-1, then to join 3 tables, you need at least 2 join conditions, but you only have 1 join condition. Every table in the from clause must be joined, but you haven't provided a join condition for the inventory table. You need to join the inventory table to either the items table or the warehouses table.
    In the code below, I have placed two dashes -- in front of each line that I added where your code was missing a line. This is just a start. There may be other errors. It would help to have the structure of your tables and an explanation and example of the results you are trying to achieve.
    SELECT Items.A,
    SUM (Items.B * Items.C) As D,
    Inventory.A,
    Warehouses.A,
    (SELECT SUM (InventoryAudit.Qty)
    FROM InventoryAudit
    -- , InventoryMain
    WHERE InventoryAudit.Item_ID = InventoryMain.Item_ID)
    FROM Inventory,
    Items,
    Warehouses
    WHERE ITEMS.A = 4
    AND Warehouses.A = Items.D
    -- AND Inventory.? = ?.?
    GROUP BY Items.A,
    Inventory.A,
    Warehouses.A;Barbara
    null

  • Sub-Select SQL query in Oracle BI Answers

    Hi
    What's the proper usage of Sub-Select SQL query in Oracle BI Answers Version Oracle Business Intelligence 10.1.3.2.1?
    I get [SQL_STATE: HY000] [nQSError: 10058] A general error has occured when trying to Sub Select query like:
    itemno = (SELECT MIN(orders.itemno) FROM mydatabase where rownum < 2 order by orders.itemno)

    Maybe the best is to create a new physical and logical object for your sub-select and join this with your current objects.

  • Sub selects in a SQL statement

    Hi, I have a query with an obsene amount of sub selects,
    for example :
    SELECT p.ID,
    (select something from data where id = p.id) data1,
    (select somelse from data2 where id = p.id) data2,
    (select someelse from data3 where id = p.id) data3,
    (select someelse from data4 where id = p.id) data4,
    (select someelse from data5 where id = p.id) data5,
    FROM property P
    WHERE ..........
    this query is taking a long time to process. Is there a more efficient way of doing such a statement?
    thanks in advance

    Gabe:
    Since the original poster said "this query is taking a long time to process", I assumed that there was a one-to-one relationship between properties and each of the dataX tables, otherwise, as you pointed out, he would be complaining about ORA-01427: single-row subquery returns more than one row
    In my union, I am returning a single column from each of the data tables (plus the id), and a NULL for each of the other columns in the in-line view. The MAX function just gets the single row for each column that actually has a value.
    As a test case, I did:
    CREATE TABLE properties AS
    SELECT rownum id, object_name
    FROM all_objects
    WHERE rownum < 11;
    CREATE TABLE data1 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data1 VALUES(1, 'ONE');
    INSERT INTO data1 VALUES(2, 'TWO');
    INSERT INTO data1 VALUES(3, 'THREE');
    CREATE TABLE data2 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data2 VALUES(4, 'FOUR');
    INSERT INTO data2 VALUES(5, 'FIVE');
    INSERT INTO data2 VALUES(6, 'SIX');
    CREATE TABLE data3 (id NUMBER, descr VARCHAR2(10));
    INSERT INTO data3 VALUES(7, 'SEVEN');
    INSERT INTO data3 VALUES(8, 'EIGHT');
    INSERT INTO data3 VALUES(9, 'NINE');The original version as posted retrieves:
    SQL> SELECT p.id, p.object_name,
      2         (SELECT descr FROM data1 WHERE id = p.id) data1,
      3         (SELECT descr FROM data2 WHERE id = p.id) data2,
      4         (SELECT descr FROM data3 WHERE id = p.id) data3
      5  FROM properties p
      6  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             93 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             10  rows processedBut, it does a SELECT (hopefully indexed) of data1, data2, and data3 for each row in properties. Minimally, 9 gets per row of properties (index root, index leaf, table row for each of data1, data2, data3) without even getting any data from properties.
    My query returns:
    SQL> SELECT p.id, p.object_name, a.data1, a.data2, a.data3
      2  FROM properties p,
      3       (SELECT id, MAX(data1) data1, MAX(data2) data2, MAX(data3) data3
      4        FROM (SELECT id, descr data1, TO_CHAR(NULL) data2, TO_CHAR(NULL) data3
      5              FROM data1
      6              UNION ALL
      7              SELECT id, TO_CHAR(NULL), descr, TO_CHAR(NULL)
      8              FROM data2
      9              UNION ALL
    10              SELECT id, TO_CHAR(NULL), TO_CHAR(NULL), descr
    11              FROM data3)
    12        GROUP BY id) a
    13  WHERE p.id = a.id(+)
    14  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             12 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              2  sorts (memory)
              0  sorts (disk)
             10  rows processedThe same result, but 1/8 of the gets. an outer join is also possible:
    SQL> SELECT p.id, p.object_name, d1.descr data1, d2.descr data2, d3.descr data3
      2  FROM properties p, data1 d1, data2 d2, data3 d3
      3  WHERE p.id = d1.id(+) AND
      4        p.id = d2.id(+) AND
      5        p.id = d3.id(+)
      6  ORDER BY p.id;
            ID OBJECT_NAME                    DATA1      DATA2      DATA3
             1 TAB$                           ONE
             2 I_IND1                         TWO
             3 I_COBJ#                        THREE
             4 USER$                                     FOUR
             5 I_OBJ1                                    FIVE
             6 I_PROXY_ROLE_DATA$_2                      SIX
             7 BOOTSTRAP$                                           SEVEN
             8 I_ICOL1                                              EIGHT
             9 UNDO$                                                NINE
            10 PROXY_ROLE_DATA$
    10 rows selected.
    Statistics
              0  recursive calls
              0  db block gets
             12 consistent gets
              0  physical reads
              0  redo size
           1000  bytes sent via SQL*Net to client
            655  bytes received via SQL*Net from client
              2  SQL*Net roundtrips to/from client
              1  sorts (memory)
              0  sorts (disk)
             10  rows processedSo, the same number of gets, and it saves one sort. But if the tables are large, multiple outer joins may not be as efficient as one outer join to the union all query.
    HTH
    John

  • Using an Aggregate Function in a Sub-SELECT

    Ok. I have this Sub-SELECT and I'd like to base my outside query based on the resyult set of my inner Sub-SELECT which contains an Aggregate function.
    Is that possible???
    Here's the Query...
    SELECT *
    FROM CUSTPRO.CPM_PND_TRAN_HDR CPMPNDTH
    INNER JOIN (SELECT CPMPNDT2.ky_pnd_seq_trans,
    CPMPNDT2.id_ba_esco,
    CPMPNDT2.ky_ba,
    CPMPNDT2.ky_enroll,
    MAX(CPMPNDT2.dt_billed_by_css)
    FROM CUSTPRO.CPM_PND_TRAN_HDR CPMPNDT2
    WHERE CPMPNDT2.ky_pnd_seq_trans IN (6544937)
    GROUP BY CPMPNDT2.ky_pnd_seq_trans,
    CPMPNDT2.id_ba_esco,
    CPMPNDT2.ky_ba,
    CPMPNDT2.ky_enroll) DERIVE1
    ON CPMPNDTH.id_ba_esco = DERIVE1.id_ba_esco
    AND CPMPNDTH.ky_ba = DERIVE1.ky_ba
    AND CPMPNDTH.ky_enroll = DERIVE1.ky_enroll
    AND CPMPNDTH.dt_billed_by_css = ????DERIVE1.MAX(CPMPNDT2.dt_billed_by_css)???
    How can I designate that last qualifier ????....
    PSULionRP

    You should give your aggregate function a column-alias as in:
    SELECT *
    FROM   custpro.cpm_pnd_tran_hdr cpmpndth
           INNER JOIN (SELECT   cpmpndt2.ky_pnd_seq_trans,
                                cpmpndt2.id_ba_esco,
                                cpmpndt2.ky_ba,
                                cpmpndt2.ky_enroll,
                                Max(cpmpndt2.dt_billed_by_css) as XXX    -- ADDED THIS.
                       FROM     custpro.cpm_pnd_tran_hdr cpmpndt2
                       WHERE    cpmpndt2.ky_pnd_seq_trans IN (6544937)
                       GROUP BY cpmpndt2.ky_pnd_seq_trans,
                                cpmpndt2.id_ba_esco,
                                cpmpndt2.ky_ba,
                                cpmpndt2.ky_enroll) derive1
             ON cpmpndth.id_ba_esco = derive1.id_ba_esco
                AND cpmpndth.ky_ba = derive1.ky_ba
                AND cpmpndth.ky_enroll = derive1.ky_enroll
                AND cpmpndth.dt_billed_by_css = derive1.XXX
    /

  • A very slow select with sub selects sql statement on Oracle

    Hi,
    I'm moving an application from MySql to Oracle. The following select were very efficiently executed in MySql. In oracle its slow like a snail.
    Do anyone have a hint on how to speed it up?
    The slow part is the four sub selects in the select part. Removing them makes the select about 50 times faster on Oracle.
    Best Regards,
    Stephane
    select
    (select count(*) from relation rr where rr.document_id = d.id and rr.product_id = ? and (rr.relation_type_id = 'link' OR rr.relation_type_id = 'product')) as relationList,
    (select count(*) from relation rr where rr.document_id = d.id and rr.product_id = ? and rr.relation_type_id = 'number') as relationNumber,
    (select count(*) from relation rr where rr.document_id = d.id and rr.product_id = ? and rr.relation_type_id = 'title') as relationTitle,
    (select count(*) from relation rr where rr.document_id = d.id and rr.product_id = ? and rr.relation_type_id = 'content') as relationText,
    d.*
    from document d,(
    select distinct r.document_id id
    from relation r
    where
    r.product_id = ?
    ) dd
    where d.id=dd.id

    You are accessing the relation-table too many times, so a rewrite to a query like this
    SQL> select dept.deptno
      2       , dept.dname
      3       , count(decode(job,'CLERK',1)) clerk
      4       , count(decode(job,'MANAGER',1)) manager
      5       , count(decode(job,'SALESMAN',1)) salesman
      6    from dept, emp
      7   where dept.deptno = emp.deptno (+)
      8   group by dept.deptno
      9       , dept.dname
    10  /
        DEPTNO DNAME               CLERK    MANAGER   SALESMAN
            10 ACCOUNTING              1          1          0
            20 RESEARCH                2          1          0
            30 SALES                   1          1          4
            40 OPERATIONS              0          0          0
    4 rijen zijn geselecteerd.will be worth the effort.
    If still not satisfied, you have to do some investigation, as described [url http://forums.oracle.com/forums/thread.jspa?threadID=501834&tstart=0]here
    Regards,
    Rob.

  • Sub-SELECT in Bulk INSERT- Performance Clarification

    I have 2 tables- emp_new & emp_old. I need to load all data from emp_old to emp_new. There is a transaction_id column in emp_new whose value needs to be fetched from a main_transaction table which also includes a Region Code column. Something like -
    TRANSACTION_ID REGION_CODE
    100 US
    101 AMER
    102 APAC
    My bulk insert query looks like this -
    INSERT INTO emp_new
    (col1,
    col2,
    transaction_id)
    SELECT
    col1,
    col2,
    *(select transaction_id from main_transaction where region_code = 'US')*
    FROM emp_old
    There would be millions of rows which need to be loaded in this way. I would like to know if the sub-SELECT to fetch the transaction_id would be re-executed for every row, which would be very costly and I'm actually looking for a way to avoid this. The main_transcation table is a pre-loaded table and its values are not going to change. Is there a way (via some HINT) to indicate that the sub-SELECT should not get re-executed for every row ?
    On a different note, the execution plan of the above bulk INSERT looks like -
    | Id | Operation | Name | Rows | Bytes | Cost (%CPU)|
    | 0 | INSERT STATEMENT | | 11M| 54M| 6124 (4)|
    | 1 | INDEX FAST FULL SCAN| EMPO_IE2_IDX | 11M| 54M| 6124 (4)|
    EMPO_IE2_IDX -> Index on emp_old
    I'm surprised to see that the table main_transaction does not feature in the execution plan at all. Does this mean that the sub-SELECT will not get re-executed for every row? However, atleast for the first read, I would assume that the table should appear in the plan.
    Can someone help me in understanding this ?

    Dear
    From 10.2, AUTOTRACE uses DBMS_XPLAN anywayYes but with the remark that it uses the estimated part of DBMS_XPLAN i.e explain plan for + select * from table(dbms_xplan.display);
    Isn'it ?
    mhouri> cl scr
    mhouri> desc t
    Name                    Null?    Type
    ID                               VARCHAR2(10)
    NAME                             VARCHAR2(100)
    mhouri> set linesize 150
    mhouri> var x number
    mhouri> exec :x:=99999
    PL/SQL procedure successfully completed.
    mhouri> explain plan for
      2  select sum(length(name)) from t where id >  :x;
    Explained.
    mhouri> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT                                                                                                                                    
    Plan hash value: 1188118800                                                                                                                          
    | Id  | Operation                    | Name | Rows  | Bytes | Cost (%CPU)| Time     |                                                                
    |   0 | SELECT STATEMENT             |      |     1 |    23 |     4   (0)| 00:00:01 |                                                                
    |   1 |  SORT AGGREGATE              |      |     1 |    23 |            |          |                                                                
    |   2 |   TABLE ACCESS BY INDEX ROWID| T    |    58 |  1334 |     4   (0)| 00:00:01 |                                                                
    |*  3 |    INDEX RANGE SCAN          | I    |    11 |       |     2   (0)| 00:00:01 |                                                                
    PLAN_TABLE_OUTPUT                                                                                                                                    
    Predicate Information (identified by operation id):                                                                                                  
       3 - access("ID">:X)                                                                                                                               
    15 rows selected.
    mhouri> set autotrace on
    mhouri> select sum(length(name)) from t where id >  :x;
    SUM(LENGTH(NAME))                                                                                                                                    
                10146                                                                                                                                    
    Execution Plan
    Plan hash value: 1188118800                                                                                                                          
    | Id  | Operation                    | Name | Rows  | Bytes | Cost (%CPU)| Time     |                                                                
    |   0 | SELECT STATEMENT             |      |     1 |    23 |     4   (0)| 00:00:01 |                                                                
    |   1 |  SORT AGGREGATE              |      |     1 |    23 |            |          |                                                                
    |   2 |   TABLE ACCESS BY INDEX ROWID| T    |    58 |  1334 |     4   (0)| 00:00:01 |                                                                
    |*  3 |    INDEX RANGE SCAN          | I    |    11 |       |     2   (0)| 00:00:01 |                                                                
    Predicate Information (identified by operation id):                                                                                                  
       3 - access("ID">:X)                                                                                                                               
    Statistics
              0  recursive calls                                                                                                                         
              0  db block gets                                                                                                                           
             15  consistent gets                                                                                                                         
              0  physical reads                                                                                                                          
              0  redo size                                                                                                                               
            232  bytes sent via SQL*Net to client                                                                                                        
            243  bytes received via SQL*Net from client                                                                                                  
              2  SQL*Net roundtrips to/from client                                                                                                       
              0  sorts (memory)                                                                                                                          
              0  sorts (disk)                                                                                                                            
              1  rows processed                                                                                                                          
    mhouri> set autotrace off
    mhouri> select sum(length(name)) from t where id >  :x;
    SUM(LENGTH(NAME))                                                                                                                                    
                10146                                                                                                                                    
    mhouri> select * from table(dbms_xplan.display_cursor);
    PLAN_TABLE_OUTPUT                                                                                                                                    
    SQL_ID  7zm570j6kj597, child number 0                                                                                                                
    select sum(length(name)) from t where id >  :x                                                                                                       
    Plan hash value: 1842905362                                                                                                                          
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |                                                                          
    |   0 | SELECT STATEMENT   |      |       |       |     5 (100)|          |                                                                          
    |   1 |  SORT AGGREGATE    |      |     1 |    23 |            |          |                                                                          
    |*  2 |   TABLE ACCESS FULL| T    |    59 |  1357 |     5   (0)| 00:00:01 |                                                                          
    Predicate Information (identified by operation id):                                                                                                  
       2 - filter(TO_NUMBER("ID")>:X)                                                                                                                    
    19 rows selected.
    mhouri> spool offBest regards
    Mohamed Houri

  • Delete statement that uses a sub-select with the statement in the cursor

    Hi all,
    How to write write a delete statement that uses a sub-select with the statement in the cursor?
    CURSOR excluded_dates IS         
           SELECT TO_TIMESTAMP(report_parameter_value, in_date_format_mask)
          INTO my_current_date_time
          FROM report_parameters
         WHERE report_parameters.report_parameter_id    = in_report_parameter_id
           AND report_parameters.report_parameter_group = 'DATE_TIME'
           AND report_parameters.report_parameter_name  = 'EXCLUDED_DATE';
    OPEN excluded_dates;
      LOOP
        FETCH excluded_dates INTO my_excluded_date;
        EXIT WHEN excluded_dates%NOTFOUND;
        DELETE FROM edr_rpt_tmp_inclusion_table
        WHERE TO_CHAR(date_time, 'mm/dd/yyyy') = TO_CHAR(my_excluded_date, 'mm/dd/yyyy');
      END LOOP;
      CLOSE excluded_dates;Thanks

    Hi,
    In such case I think is better to create a view an perform the delete using it. Example (using HR schema):
    Connected to Oracle Database 10g Express Edition Release 10.2.0.1.0
    Connected as hr
    SQL> create or replace view v_employees as select * from employees where first_name like 'J%';
    View created
    SQL> select * from v_employees;
    EMPLOYEE_ID FIRST_NAME           LAST_NAME                 EMAIL                     PHONE_NUMBER         HIRE_DATE   JOB_ID         SALARY COMMISSION_PCT MANAGER_ID DEPARTMENT_ID
            110 John                 Chen                      JCHEN                     515.124.4269         28/09/1997  FI_ACCOUNT    8200,00                       108           100
            112 Jose Manuel          Urman                     JMURMAN                   515.124.4469         07/03/1998  FI_ACCOUNT    7800,00                       108           100
            125 Julia                Nayer                     JNAYER                    650.124.1214         16/07/1997  ST_CLERK      3200,00                       120            50
            127 James                Landry                    JLANDRY                   650.124.1334         14/01/1999  ST_CLERK      2400,00                       120            50
            131 James                Marlow                    JAMRLOW                   650.124.7234         16/02/1997  ST_CLERK      2500,00                       121            50
            133 Jason                Mallin                    JMALLIN                   650.127.1934         14/06/1996  ST_CLERK      3300,00                       122            50
            139 John                 Seo                       JSEO                      650.121.2019         12/02/1998  ST_CLERK      2700,00                       123            50
            140 Joshua               Patel                     JPATEL                    650.121.1834         06/04/1998  ST_CLERK      2500,00                       123            50
            145 John                 Russell                   JRUSSEL                   011.44.1344.429268   01/10/1996  SA_MAN       14000,00           0,40        100            80
            156 Janette              King                      JKING                     011.44.1345.429268   30/01/1996  SA_REP       10000,00           0,35        146            80
            176 Jonathon             Taylor                    JTAYLOR                   011.44.1644.429265   24/03/1998  SA_REP        8600,00           0,20        149            80
            177 Jack                 Livingston                JLIVINGS                  011.44.1644.429264   23/04/1998  SA_REP        8400,00           0,20        149            80
            181 Jean                 Fleaur                    JFLEAUR                   650.507.9877         23/02/1998  SH_CLERK      3100,00                       120            50
            186 Julia                Dellinger                 JDELLING                  650.509.3876         24/06/1998  SH_CLERK      3400,00                       121            50
            189 Jennifer             Dilly                     JDILLY                    650.505.2876         13/08/1997  SH_CLERK      3600,00                       122            50
            200 Jennifer             Whalen                    JWHALEN                   515.123.4444         17/09/1987  AD_ASST       4400,00                       101            10
    16 rows selected
    SQL> delete from v_employees where hire_date >= to_date('01/06/1998', 'dd/mm/yyyy');
    2 rows deleted
    SQL> regards,

  • Concat result of a sub-select in a single field

    How can I concat all registers of a sub-select in a single field.
    like:
    SELECT DATE_MARK
    FROM TABLE_A
    WHERE COD = '123'
    RESULT:
    200601
    200605
    200607
    200507
    How can I put that result in a single field? like this:
    '200601 200605 200607 200507'
    Thanks.

    In a little different approach ->
    satyaki>
    satyaki>select * from v$version;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod
    PL/SQL Release 10.2.0.3.0 - Production
    CORE    10.2.0.3.0      Production
    TNS for 32-bit Windows: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    Elapsed: 00:00:00.01
    satyaki>
    satyaki>
    satyaki>drop type pipe_rec;
    Type dropped.
    Elapsed: 00:00:05.47
    satyaki>
    satyaki>
    satyaki>create or replace type pipe_obj as object
      2    (
      3      dno       number(5),
      4      buff      clob
      5    );
      6  /
    Type created.
    Elapsed: 00:00:00.24
    satyaki>
    satyaki>create or replace type pipe_rec as table of pipe_obj;
      2  /
    Type created.
    Elapsed: 00:00:00.17
    satyaki>
    satyaki>
    satyaki>create or replace function pivot_horizon(d_no  in number)
      2  return pipe_rec
      3  pipelined is
      4    cursor c1
      5    is
      6      select ename
      7      from emp
      8      where deptno = d_no;
      9     
    10   r1 c1%rowtype;
    11  
    12   str clob;
    13  begin
    14    str:= '';
    15    for r1 in c1
    16    loop
    17      str := str||' '||r1.ename;
    18    end loop;
    19      pipe row(pipe_obj(d_no,trim(str)));
    20    return;
    21  end;
    22  /
    Function created.
    Elapsed: 00:00:00.18
    satyaki>
    satyaki>
    satyaki>
    satyaki>
    satyaki>select *
      2  from table(cast(pivot_horizon(10) as pipe_rec));
           DNO BUFF
            10 SOURAV  CLARK KING
    Elapsed: 00:00:00.11
    satyaki>
    satyaki>
    satyaki>Regards.
    Satyaki De.

  • Sub-Select Count query breaking TOAD

    Oracle 10.2.0.4.0
    Running TOAD 9.1
    I am running some SQL on our eBusiness Suite:
    SELECT pha.segment1
         , pha.type_lookup_code
         , (SELECT COUNT(DISTINCT pha2.po_header_id)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) po_count
         , (SELECT MAX(pha2.creation_date)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) latest_cpa_po
      FROM po.po_headers_all pha
         , po.po_vendors pv
         , po.po_vendor_sites_all pvsa
    WHERE pha.vendor_id = pv.vendor_id
       AND pha.vendor_site_id = pvsa.vendor_site_id
    --   AND pv.VENDOR_NAME LIKE 'H%'
       AND pha.vendor_id = 98
       AND pha.type_lookup_code = 'CONTRACT'
       AND pha.org_id IN(7041, 7042);The above query runs quicky (approx. 1 second). If I take out the AND pha.vendor_id = 98 then the query takes a few minutes to run.
    When I try to export it, or scroll down to view > 500 rows, TOAD crashes.
    I know this isn't a TOAD forum, but I think that this is probably an issue with my no doubt rubbish SQL.
    If I take out this sub-select, then the problem doesn't happen:
         , (SELECT COUNT(DISTINCT pha2.po_header_id)
              FROM po.po_headers_all pha2
                 , po.po_lines_all pla
             WHERE pha2.po_header_id = pla.po_header_id
               AND pla.contract_id = pha.po_header_id) po_countHowever, I can't work out a better way of getting the data I need.
    The sub-select counts POs which have been raised where the contractID on the PO line is the same as the PO Header ID from the main query.
    Any advice please, on what I could do to sort this out would be much appreciated.
    Thanks!

    Hi,
    It looks like you can replace both scalar sub-queries with a join, like this:
    WITH     header_lines_summary     AS
         SELECT    pla.contract_id
              ,       COUNT (DISTINCT pha2.po_header_id)     AS po_count
              ,       MAX (pha2.creation_date)          AS latest_cpa_po
              FROM        po.po_headers_all pha2
                 ,        po.po_lines_all   pla
             WHERE        pha2.po_header_id = pla.po_header_id
          GROUP BY       pla.contract_id
    )                                        -- Everything up to this line is new
    SELECT pha.segment1
         , pha.type_lookup_code
         , hls.po_count                              -- Changed
         , hls.latest_cpa_po                         -- Changed
      FROM po.po_headers_all     pha
         , po.po_vendors           pv
         , po.po_vendor_sites_all      pvsa
         , header_lines_summary     hls                    -- New
    WHERE pha.vendor_id          = pv.vendor_id
       AND pha.vendor_site_id     = pvsa.vendor_site_id
       AND pha.po_header_id          = hls.contract_id (+)          -- New
    --   AND pv.VENDOR_NAME      LIKE 'H%'
       AND pha.vendor_id           = 98
       AND pha.type_lookup_code      = 'CONTRACT'
       AND pha.org_id           IN (7041, 7042);Aside from the sub-query (which is entirely new), the query above is just what you posted, with 2 lines changed and 2 lines added, as marked.
    This should be more efficient, but I don't know for certain that it will solve the Toad problem.
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables, and also post the results you want from that data.
    It never hurts to say what version of Oracle you're using.

  • Sub select in Oracle

    We have procedure in MSSQL where we use sub select. I was
    wondering if there is a way to implement it in Oracle. I tried
    creating one , but failed . Any helpwill be appreciated.
    /*IN ORACLE*/
    create or replace package testpkg as
    type r1rec is record
    (name test1.name%type,
    age test2.age%type);
    type r1RefCur is ref cursor return r1rec;
    Procedure testproc
    (r1ref In OUT r1Refcur);
    end;
    create or replace package body testpkg as
    Procedure testproc
    (r1ref In OUT r1Refcur) is
    begin
    open r1ref for
    select name,(select age from test2) from test1;
    end;
    end;
    null

    Anish,
    Here are a couple of pointers:
    select empno, (select dname from dept) dname from emp
    ERROR at line 1:
    ORA-01427: single-row subquery returns more than one row
    SQL> select empno, (select MAX(dname) from dept) dname from emp
    2 ;
    EMPNO DNAME
    2 SALES
    7499 SALES
    7521 SALES
    This is a new feature so may not be available in all
    circumstances. (eg it may not work in the cursor statement you
    suggested)
    There is an older way of doing it:
    SQL> select empno, d.mdname from emp, (select MAX(dname) mdname
    from dept) d;
    EMPNO MDNAME
    2 SALES
    7499 SALES
    Otherwise a conversion into a more frequently used type syntax
    may be required select col1, col2 from tab1, tab2 where ....
    [the where clause may need a bit of thought]
    I hope this is of some help
    Turloch
    Oracle Migration Workbench Team
    Anish (guest) wrote:
    : We have procedure in MSSQL where we use sub select. I was
    : wondering if there is a way to implement it in Oracle. I tried
    : creating one , but failed . Any helpwill be appreciated.
    : /*IN ORACLE*/
    : create or replace package testpkg as
    : type r1rec is record
    : (name test1.name%type,
    : age test2.age%type);
    : type r1RefCur is ref cursor return r1rec;
    : Procedure testproc
    : (r1ref In OUT r1Refcur);
    : end;
    : create or replace package body testpkg as
    : Procedure testproc
    : (r1ref In OUT r1Refcur) is
    : begin
    : open r1ref for
    : select name,(select age from test2) from test1;
    : end;
    : end;
    Oracle Technology Network
    http://technet.oracle.com
    null

  • Using XML in sub select

    Hmmmm
    Stuck again, it seems as though I am not the sharpest tool in the box when it comes to XML. Boss seems to love XML though....
    In SQL I have the ability to do something similar to the following :
    SELECT * FROM JOBS
    WHERE JOB_ID IN(SELECT JOB_ID WHERE ACTIVE = 1)
    In this scenario no real need to do a sub select however it demonstrates my point.
    Is it possible to achive this using an XML document in my sub select?
    eg something like
    SELECT * FROM JOBS WHERE JOB_ID IN(EXTRACTVALUE(var,xpath JOB_ID)
    If I had a big list would this iterate through each instance of the value I want to join on???

    Have a look at the XML DB technical whitepaper
    http://otn.oracle.com/tech/xml/xmldb/Current/TWP.pdf
    QUERYING AND INDEXING XML WITH ORACLE XML DB on Page 49
    In particular the queries on Page 51

  • Sub-selects in forms causing ora-24333

    We are running in a new 11g environment and are receiving an ora-24333 from forms with sub-selects. The same form works in 10g and the sql statement, itself, works in sqlplus. The following is an example of code
    exec_sql.parse(oracle_handle, oracle_cursor,
    'update vendor a
    set (status, vendor_type) =
    (select decode(rec_sttus,'||''' '''||','||'''ACTIVE'''||',
    '||'''I'''||','||'''INACTIVE'''||',
    '||'''D'''||','||'''DELETE'''||',
    '||'''F'''||','||'''FOREIGN'''||',
    '||'''N'''||','||'''RENUMBERED'''||',
    '||'''K'''||','||'''KEEPER'''||',
    rec_sttus),
    vndr_type
    from prch_vndr b
    where a.vendor_no = b.vndr_num)
    where vendor_no in
    (select vndr_num
    from prch_vndr)');
    t_temp := exec_sql.execute(oracle_handle, oracle_cursor);
    exec_sql.parse(oracle_handle, oracle_cursor, 'commit');
    t_temp := exec_sql.execute(oracle_handle, oracle_cursor);
    Any ideas where we might have a configuration setting missing or what has changed with 11g forms of which we are unaware?
    Edited by: kwalker on Dec 26, 2012 2:00 PM
    Edited by: kwalker on Dec 26, 2012 2:00 PM

    Hi Kelly,
    We are running in a new 11g environment and are receiving an ora-24333 from forms with sub-selects. The same form works in 10g and the sql statement, itself, works in sqlplus. The following is an example of codeAlways post code snippets in &#123;code&#125; tags as explained in FAQ.
    >
    exec_sql.parse(oracle_handle, oracle_cursor,
    'update vendor a
    set (status, vendor_type) =
    (select decode(rec_sttus,'||''' '''||','||'''ACTIVE'''||',
    '||'''I'''||','||'''INACTIVE'''||',
    '||'''D'''||','||'''DELETE'''||',
    '||'''F'''||','||'''FOREIGN'''||',
    '||'''N'''||','||'''RENUMBERED'''||',
    '||'''K'''||','||'''KEEPER'''||',
    rec_sttus),
    vndr_type
    from prch_vndr b
    where a.vendor_no = b.vndr_num)
    where vendor_no in
    (select vndr_num
    from prch_vndr)');
    t_temp := exec_sql.execute(oracle_handle, oracle_cursor);
    exec_sql.parse(oracle_handle, oracle_cursor, 'commit');
    t_temp := exec_sql.execute(oracle_handle, oracle_cursor);Any ideas where we might have a configuration setting missing or what has changed with 11g forms of which we are unaware?>
    a. EXEC_SQL package for simple updates looks like an overkill. EXECUTE IMMEDIATE will meet the requirement.
    b. The ORA-24333 error is related to data. Is the database and schema for 10g, SQLDeveloper and 11g the same? If they are different then check data in the database/schema used with Forms 11g.
    Cheers,

  • Delete with sub select sometimes slow

    Hi all,
    we have following problem in version 11.2:
    we run some deletes similar delete-statements:
    delete from msvs where fk_msv_nr in (select pk_msv_nr from msv where rueckweisungsgrund = '<Falsch aus ePUB angelegt>');
    delete from zbe where fk_msv_nr in (select pk_msv_nr from msv where rueckweisungsgrund = '<Falsch aus ePUB angelegt>');
    delete from zag where fk_msv_nr in ( select  pk_msv_nr from msv where rueckweisungsgrund = '<Falsch aus ePUB angelegt>');
    table msv has 500000 rows, the select has 390000 rows and is running a few seconds, seems good.
    table msvs has 1000000 rows, zbe 3250000 rows and zag 513000 rows
    pk_msv_nr is primary key on msv
    fk_msv_nr is foreign key and referencing table msv
    delete from msvs: 780000 rows, 55sec
    delete from zbe: 2885000 rows 5min 55sec
    delete from zag: process killed after 30min
    execution plan shows FTS on msv and index range scan on idx_zag_fk_msv_nr (foreign key)
    also i see more than 100'000'000 logical reads
    we have similar problem with one other table
    Anybody an idea, why the deletes on two tables are slow, a few other tables (all with same sub-select) are in time
    Thanks for any help!!!
    Regards
    Jürgen

    SQL> explain plan for
      2  delete from msvs where fk_msv_nr in (select pk_msv_nr from msv where rueckweisungsgrund = '<Falsch aus ePUB angelegt>');
    Explained.
    Elapsed: 00:00:00.21
    SQL> @?/rdbms/admin/utlxpls
    PLAN_TABLE_OUTPUT
    | Id  | Operation          | Name              | Rows  | Bytes | Cost  |
    |  0 | DELETE STATEMENT    |                    |    1 |    21 |  2202 |
    |  1 |  DELETE            | MSVS              |      |      |      |
    |  2 |  NESTED LOOPS      |                    |    1 |    21 |  2202 |
    |  3 |    TABLE ACCESS FULL| MSV                |    1 |    7 |  2200 |
    |  4 |    INDEX RANGE SCAN | IDX_UNIQUE_MSVS_PK |    2 |    28 |    2 |
    SQL>  explain plan for
      2  delete from zbe where fk_msv_nr in (select pk_msv_nr from msv where rueckweisungsgrund = '<Falsch aus ePUB angelegt>');
    Explained.
    Elapsed: 00:00:00.09
    SQL>  @?/rdbms/admin/utlxpls
    PLAN_TABLE_OUTPUT
    | Id  | Operation           | Name              | Rows  | Bytes | Cost  |
    |   0 | DELETE STATEMENT    |                   |     3 |    78 |  2202 |
    |   1 |  DELETE             | ZBE               |       |       |       |
    |   2 |   NESTED LOOPS      |                   |     3 |    78 |  2202 |
    |   3 |    TABLE ACCESS FULL| MSV               |     1 |     7 |  2200 |
    |   4 |    INDEX RANGE SCAN | IDX_UNIQUE_ZBE_PK |     7 |   133 |     2 |
    SQL>  explain plan for
      2  delete from zag where fk_msv_nr in ( select  pk_msv_nr from msv where rueckweisungsgrund = '<Falsch aus ePUB angelegt>');
    Explained.
    SQL> @?/rdbms/admin/utlxpls
    PLAN_TABLE_OUTPUT
    | Id  | Operation           | Name              | Rows  | Bytes | Cost  |
    |   0 | DELETE STATEMENT    |                   |     1 |    27 |  2202 |
    |   1 |  DELETE             | ZAG               |       |       |       |
    |   2 |   NESTED LOOPS      |                   |     1 |    27 |  2202 |
    |   3 |    TABLE ACCESS FULL| MSV               |     1 |     7 |  2200 |
    |   4 |    INDEX RANGE SCAN | IDX_ZAG_FK_MSV_NR |     3 |    60 |     2 |

  • Speed Issue on an UPDATE from a sub-select

    Ignoring the fact this is a Spatial Query... having troubles understanding why a select finishes very quickly, yet putting the same select syntax in an UPDATE command as a sub-select takes forever to finish. Columns in the original table are indexed (ie SANITARY_MH_DATA.GIS_ID). The work-around has been to load a Temporary table with the sub-select results, followed by an UPDATE command. But it creates more sql code than needed.
    Any hints appreciated.
    Phil.
    -- FIND THE SANITARY CATCHMENT THE MANHOLE IS IN --
    -- need to add the ones that fall into more than 1 catchment
    -- with the mask=TOUCH
    UPDATE SANITARY_MH_DATA SET CATCHMENT_NAME = '';
    -- THIS BLAZES AND IS DONE IN 5 SECONDS...
    SELECT CATCHMENT_ID FROM
    (SELECT A.GIS_ID AS MANHOLE, B.GIS_ID AS CATCHMENT_ID
    FROM SANITARY_MH A, SANITARY_CATCHMENT B
    WHERE SDO_RELATE (A.GEOMETRY,B.GEOMETRY, 'mask=INSIDE querytype=Window') = 'TRUE');
    -- THIS BOGS DOWN AND TAKES FOREVER TO FINISH...
    UPDATE SANITARY_MH_DATA SET CATCHMENT_NAME = ( SELECT CATCHMENT_ID FROM
    (SELECT A.GIS_ID AS MANHOLE, B.GIS_ID AS CATCHMENT_ID
    FROM SANITARY_MH A, SANITARY_CATCHMENT B
    WHERE SDO_RELATE (A.GEOMETRY,B.GEOMETRY, 'mask=INSIDE querytype=Window') = 'TRUE')
    WHERE SANITARY_MH_DATA.GIS_ID = A.MANHOLE);
    EXIT;
    Edited by: user13174287 on 24-Aug-2010 3:51 PM
    Edited by: user13174287 on 24-Aug-2010 4:06 PM

    There is such a way, however I doubt that it will work in your case. There are some restrictions on it.
    You can write an update to a kind of inline query.
    UPDATE (select dat.*, mh.GIS_ID AS MANHOLE, cat.GIS_ID CATCHMENT_ID
           from SANITARY_MH_DATA dat,  SANITARY_MH mh, SANITARY_CATCHMENT cat
           where SDO_RELATE (mh.GEOMETRY,cat.GEOMETRY, 'mask=INSIDE querytype=Window') = 'TRUE'
           and dat.GIS_ID = mh.GIS_ID
           ) v
    SET v.CATCHMENT_NAME = v.CATCHMENT_ID
    WHERE (v.CATCHMENT_NAME != v.CATCHMENT_ID or v.CATCHMENT_NAME is null)
    ;there is some join criteria missing between cat and dat. MAybe it would work if the CATACHMENT ID is fetched in the selct clause of the inline view, instead of joining it.
    UPDATE (select dat.*, mh.GIS_ID AS MANHOLE,
                        (select cat.GIS_ID from SANITARY_CATCHMENT cat
                         where SDO_RELATE (mh.GEOMETRY,cat.GEOMETRY, 'mask=INSIDE querytype=Window') = 'TRUE'
                         and rownum = 1) as catchment_id
           from SANITARY_MH_DATA dat,  SANITARY_MH mh
           where dat.GIS_ID = mh.GIS_ID
           ) v
    SET v.CATCHMENT_NAME = v.CATCHMENT_ID
    WHERE (v.CATCHMENT_NAME != v.CATCHMENT_ID or v.CATCHMENT_NAME is null)
    ;Oh and there is the MERGE statement. This might help in your case.
    Edited by: Sven W. on Aug 25, 2010 9:19 PM

Maybe you are looking for

  • Wavy lines in bar charts after converting a Powerpoint to a pdf?

    After converting a Powerpoint file to a pdf, the bar charts have wavy lines.  The one thing I noticed is that the problem appeared when creating the pdf with Notes showing.  If Notes are turned off, then the bars are fine. Is there a solution for thi

  • How to convert from ifs date format to sql based dates

    I want to write a sql query using dates, to search an ifs database. Ifs stores dates as numbers created using the java.util.Date class. These dates are accurate to seconds. PLSQL uses a different format. What I need is a PLSQL function that converts

  • Query, infoset and Logical database tuning?

    Hi, All: I created infoset z_infoset based on logical database DDF. then based on infoset z_query based on infoset z_infoset. then run the z_query, the performance is too bad. take long time. How to tuning logical database, infoset and query. Thanks,

  • Malfunctioning Macbook Pro Trackpad

    Okay. I have a 15" MBP from mid 2009. It's worked nearly perfectly thus far, but today it started to have major issues with the trackpad (the trackpad built in, not an external TrackPad). The curser skips around a lot... sometimes it responds correct

  • Kdeinit4 crashes on logout

    Hello guys, I have a problem with kdeinit4, it keeps crashing when I logout. This is the gdb output. Application: Shell del desktop di Plasma (kdeinit4), signal: Segmentation fault [Current thread is 1 (Thread 0x7f85d0652760 (LWP 1154))] Thread 2 (Th