Aggregate function in native query (EJB 3.0)

How do you run a aggregate function in a native query? I have a particular use case, for reporting purposes, where the result set is too large to fetch the actual CMP collection, thus I need to execute a native count/avg select. I want some thing like,
Integer totalRecords = (Integer)
       em.createNativeQuery("select count(*) from records").getSingleResult();

Oracle is intelligent enough to use index only if query result filtering is based on it and result set is less than 5% of the total data set.Sorry to be blunt but that 5% stuff is nonsense.
Here since the index column is not used in the WHERE clause, oracle performs full table scan.That's not true either. Under the right circumstances the optimizer can use the index, even without a WHERE clause in the query:
SQL> create table t as select * from dba_objects where object_type is not null;
Table created.
SQL> alter table t modify object_type not null;
Table altered.
SQL> create index t_idx on t(object_type);
Index created.
SQL> explain plan for
  2  select object_type, count(*) from t group by object_type;
Explained.
| Id  | Operation             | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
|   0 | SELECT STATEMENT      |       |    44 |   396 |    60   (7)| 00:00:01 |
|   1 |  HASH GROUP BY        |       |    44 |   396 |    60   (7)| 00:00:01 |
|   2 |   INDEX FAST FULL SCAN| T_IDX | 72474 |   636K|    57   (2)| 00:00:01 |
-------------------------------------------------------------------------------With the OP's query, it (apparently) can not be satisfied by using only the index.
WHERE TO_CHAR(COL) = TO_CHAR(COL)I don't even know what this means. Usually if you perform a function on an indexed column, the optimizer will not use the index (unless of course it's an fbi).

Similar Messages

  • Error in using aggregate function in Outer Query in Siebel Analytics

    Hi,
    When I am using aggregate function in outer query in Siebel Analytics I am facing error.
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 59111] The SQL statement must include a GROUP BY clause. (HY000)
    Bellow is the code.
    SELECT test1.username saw_0, test1.desg saw_1,COUNT (test2.querydate) saw_2
    FROM (SELECT POSITION.CBL username,
    POSITION.CBP desg
    FROM "CM"
    WHERE (POSITION.BPTCD = 'Marketing')
    AND (POSITION.EDate =TIMESTAMP '1899-01-01 00:00:00'
    ) test1,
    (SELECT users.UN username,
    measures."Query Count" querycount,
    measures."Max Total Time" secs,
    topic.db dashboardname,
    "Query Time".DATE querydate
    FROM "Plan"
    WHERE (topic."Dashboard Name" IN ('DS'))) test2
    WHERE test2.username = LOWER (test1.username)
    AND test2.dashboardname = 'DS'
    GROUP BY test1.username, test1.desg

    Should your query be a valid SQL query?
    I can't think that the query you have would be valid in a SQL plus window.
    Chris

  • Any difference between distinct and aggregate function in sql query cost???

    Hi,
    I have executed many sql stmts patterns- such as:
    a) using a single table
    b) using two tables, using simple joins or outer joins
    but i have not noticed any difference in sql stmts in cost and in execution plan....
    Anyway, my colleague insists on that using aggregate function is less costly compared to
    distinct....(something i have not confirmed, that's why i beleive that they are exactly the same...)
    For the above reffered 1st sql pattern.. we could for example use
    select distinct deptno
    from emp
    select count(*), deptno
    from emp
    group by deptno select distinct owner, object_type from all_objects
    select count(*), owner, object_type from all_objects
    group by owner, object_typeHave you found any difference between the two ever...????
    Note: I use Ora DB 10g v2.
    Thank you,
    Sim

    distinct and aggregate function are for different uses and may give same result but if u r using aggregate function to get distinct records, it will be expensive...
    ex
    select distinct deptno from scott.dept;
    Statistics
    0 recursive calls
    0 db block gets
    2 consistent gets
    0 physical reads
    0 redo size
    584 bytes sent via SQL*Net to client
    488 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    0 sorts (memory)
    0 sorts (disk)
    4 rows processed
    select deptno from scott.emp group by deptno;
    Statistics
    307 recursive calls
    0 db block gets
    60 consistent gets
    6 physical reads
    0 redo size
    576 bytes sent via SQL*Net to client
    488 bytes received via SQL*Net from client
    2 SQL*Net roundtrips to/from client
    6 sorts (memory)
    0 sorts (disk)
    3 rows processed
    Nimish Garg
    Software Developer
    *(Oracle & ASP.NET)*
    Indiamart Intermesh Limited, Noida
    To Get Free Oracle & ASP.NET Code Snippets
    Follow: http://nimishgarg.blogspot.com

  • Aggregate function in the query

    Hi gurus,
    What makes presentation layer send queries with Aggregate( by ) function eventhough this function is not used in the column formulas?
    Now comes a long explanation - only for the patient ones :-)
    I am working OBIEE / Essbase.
    A strange thing happened to one of my reports - exactly the same report (pivot) in production (old repository) works fine, but brings wrong results on the new repository.
    I found out that SQL sent to OBIEE is different.
    With old repository, it sends a query with 'Aggregate ( by)' function used for measures. However with the new one, it sends just column names without the Aggregate.
    Where shall I look for the difference?
    -- OLD (Good) query -----------
    SELECT DIM_BATCH_HEADERS."Gen3,DIM_BATCH_HEADERS" saw_0,
    PROD_QTY.PROD_ACTUAL_QTY_KG/1000 saw_1,
    DIM_COMPONENT."Gen3,DIM_COMPONENT" saw_2, ' ' saw_3,
    COST.COMP_ACTUAL_COST_ILS_PER_TON saw_4, 0 saw_5,
    COST.ACTUAL_COST_K_ILS saw_6, 0 saw_7,
    AGGREGATE(saw_1 BY ),
    AGGREGATE(saw_4 BY ),
    AGGREGATE(saw_6 BY ),
    AGGREGATE(saw_1 BY saw_0, saw_5),
    AGGREGATE(saw_4 BY saw_0, saw_5),
    AGGREGATE(saw_6 BY saw_0, saw_5)
    FROM "COP_MAAD#1" WHERE (COMP_QTY.COMP_RELEVANT > 0)
    AND (DIM_TIME."YEAR" = '2009')
    AND (DIM_BATCH_HEADERS."Gen2,DIM_BATCH_HEADERS" = 'ABC')
    ORDER BY saw_1 DESC, saw_4 DESC, saw_0, saw_2, saw_3, saw_5, saw_7
    -- NEW (Incorrect) Query ---------------
    SELECT DIM_BATCH_HEADERS."Gen3,DIM_BATCH_HEADERS" saw_0,
    PROD_QTY.PROD_ACTUAL_QTY_KG/1000 saw_1,
    DIM_COMPONENT."Gen3,DIM_COMPONENT" saw_2,
    ' ' saw_3, COST.COMP_ACTUAL_COST_ILS_PER_TON saw_4,
    0 saw_5,
    COST.ACTUAL_COST_K_ILS saw_6,
    0 saw_7 FROM "COP_MAAD#1"
    WHERE (COMP_QTY.COMP_RELEVANT > 0) AND (DIM_TIME."YEAR" = '2009')
    AND (DIM_BATCH_HEADERS."Gen2,DIM_BATCH_HEADERS" = 'ABC') ORDER BY saw_1 DESC, saw_4 DESC
    Thanks,
    Alex

    Hi,
    Can anybody reply to the above question please?
    regards,
    Siva

  • How to use multiple aggregate functions in single query

    hi to all
    The output will be giving first_name,last_name,max(salary),min(salary) and the output will be department wise.From employees table in single query
    output will be:
    first_name|last_name|max(salary)|min(salary)

    SELECT first_name||' '||last_name as ename,
           MIN(sal) KEEP (DENSE_RANK FIRST ORDER BY sal) OVER (PARTITION BY deptno) "Lowest",
           MAX(sal) KEEP (DENSE_RANK LAST ORDER BY sal) OVER (PARTITION BY deptno) "Highest"
    FROM   emp
    ORDER BY deptno, sal;Edited by: Ramio on Jan 10, 2012 10:43 PM

  • EJB 3.0: EJBQL aggregate functions not working properly

    Hi!
    We are experiencing problems when using aggregate functions within EJBQL queries. In my case, we have to use max() function to retrieve the max start_date from a specific table. In order to do this, we wrote the following code:
    String strQuery = "select max(o.dt_fim) from Questionario o";
    Query queryTeste = em.createQuery(strQuery);
    List x = queryTeste.getResultList();
    OBS: dt_fim is an Oracle 10g datetime column, with its corresponding entity attribute in Questionario entity class.
    AFAIK, the query above should return only one record (object instance) containing the date value, right? However, it brougth a list of the entity objects, corresponding to all records in the table, as we had just run "select o from Questionario o".
    Examining the server log we can see this behavior:
    [TopLink Fine]:2006.09.12 01:47:55.526--
    ServerSession(7119662)--Connection(7048401)--Thread(Thread[ApplicationServerThread-0,5,RequestThreadGroup])
    --SELECT ID_QUEST, DT_INICIO, DT_FIM, DS_QUEST, DT_CRIACAO, TP_QUEST, NM_QUEST, COD_SEGMENTO, ID_GRUPO FROM TBBOP_QUEST
    Are anyone experiencing this issue?
    Is there any workaround?
    Any help would be much appreciated, since we need to deploy the application for user testing asap.
    Thanks in advance.
    Best regards,
    Gustavo
    PS: We are using JDeveloper 10.1.3.0.4(SU4)
    Message was edited by:
    Gustavo Lopes Sobral

    The 10.1.3.0 versions of JDeveloper contain our early preview of EJB 3.0 JPA functionality. One limitation is that the query language is not complete (released before the spec was finalized).
    You can use TopLink Essentials (JPA Reference implementation) whihc contains a complete compliant implementation of the final specification.
    http://otn.oracle.com/jpa
    The 10.1.3.1 JDeveloper preview ships with TopLink Essentials.
    Doug

  • Problem while using aggregate functions in EJB QL 2.1

    Hai all,
       I am using aggregate function as follows
       select max(c.id) from customer as c
      for this iam selected check box EJB QL 2.1 in persistent.xml
      this is validated by nwds, but while deploying server raising error like ejb ql syntax error.
      Actually according to EJB QL 2.1 this is a valid query, what i need to do for run this same query .
      Anybody please help me in this regard
    Regards
    Somaraju

    Beevin
      Both two are not even validated,
      but with the first one as select max(c.id) from customer as c , in this case it is validated but while deploying it is error as , object must be return
      But when i saw  the ejb2.1 specification we can write this type of queries also ?
      Is it problem with was any thing
    Regards
    Somaraju

  • Need complex query  with joins and AGGREGATE  functions.

    Hello Everyone ;
    Good Morning to all ;
    I have 3 tables with 2 lakhs record. I need to check query performance.. How CBO rewrites my query in materialized view ?
    I want to make complex join with AGGREGATE FUNCTION.
    my table details
    SQL> select from tab;*
    TNAME TABTYPE CLUSTERID
    DEPT TABLE
    PAYROLL TABLE
    EMP TABLE
    SQL> desc emp
    Name
    EID
    ENAME
    EDOB
    EGENDER
    EQUAL
    EGRADUATION
    EDESIGNATION
    ELEVEL
    EDOMAIN_ID
    EMOB_NO
    SQL> desc dept
    Name
    EID
    DNAME
    DMANAGER
    DCONTACT_NO
    DPROJ_NAME
    SQL> desc payroll
    Name
    EID
    PF_NO
    SAL_ACC_NO
    SALARY
    BONUS
    I want to make  complex query  with joins and AGGREGATE  functions.
    Dept names are : IT , ITES , Accounts , Mgmt , Hr
    GRADUATIONS are : Engineering , Arts , Accounts , business_applications
    I want to select records who are working in IT and ITES and graduation should be "Engineering"
    salary > 20000 and < = 22800 and bonus > 1000 and <= 1999 with count for males and females Separately ;
    Please help me to make a such complex query with joins ..
    Thanks in advance ..
    Edited by: 969352 on May 25, 2013 11:34 AM

    969352 wrote:
    why do you avoid providing requested & NEEDED details?I do NOT understand what do you expect ?
    My Goal is :
    1. When executing my own query i need to check expalin plan.please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9010.htm#SQLRF01601
    2. IF i enable query rewrite option .. i want to check explain plan ( how optimizer rewrites my query ) ? please proceed to do so
    http://docs.oracle.com/cd/E11882_01/server.112/e16638/ex_plan.htm#PFGRF009
    3. My only aim is QUERY PERFORMANCE with QUERY REWRITE clause in materialized view.It is an admirable goal.
    Best Wishes on your quest for performance improvements.

  • Pivot type query without aggregate function. Transposing

    Hi experts,
    Oracle 11g.
    I have a table (see code example to reproduce), that has a date, a grouping, and the count of that grouping (determined in another query). I need a pivot type query, but, without the aggregate functions. This is just for a report display. I can not seem to figure this one out. Thanks for your help.
    CREATE TABLE temp_task
    AS
       SELECT TO_DATE ('15-NOV-2012') validation_date,
              'GROUP 1' AS group_number,
              42 AS monthly_count
         FROM DUAL
       UNION ALL
       SELECT TO_DATE ('14-DEC-2012') validation_date,
              'GROUP 1' AS group_number,
              33 AS monthly_count
         FROM DUAL
       UNION ALL
       SELECT TO_DATE ('15-NOV-2012') validation_date,
              'GROUP 2' AS group_number,
              10 AS monthly_count
         FROM DUAL
       UNION ALL
       SELECT TO_DATE ('14-DEC-2012') validation_date,
              'GROUP 2' AS group_number,
              32 AS monthly_count
         FROM DUAL
       UNION ALL
       SELECT TO_DATE ('15-NOV-2012') validation_date,
              'GROUP 3' AS group_number,
              7 AS monthly_count
         FROM DUAL
       UNION ALL
       SELECT TO_DATE ('14-DEC-2012') validation_date,
              'GROUP 3' AS group_number,
              9 AS monthly_count
         FROM DUAL;Using only SQL I need to return the following:
    VALIDATION_DATE | GROUP 1 | GROUP 2 | GROUP 3
    11/15/2012 | 42 | 10 | 7
    12/14/2012 | 33 | 32 | 9

    Hi
    You always need to use an aggregate function while pivoting.
    Even if you don't really need any aggregation, that is, when what you see in the table is what you'll get in the result set, you still have to use an aggregate function. If there will only be one value contrinuting to each cell, then you can use MIN or MAX. It won't matter which; since there's only 1 value, that value will be the highest of the 1, and it will also be the lowest. For NUMBER columns, you could also use SUM or AVG.
    SELECT       *
    FROM       temp_task
    PIVOT       ( MIN (monthly_count)
             FOR group_number IN ( 'GROUP 1'
                                 , 'GROUP 2'
                        , 'GROUP 3'
    ORDER BY  validation_date
    ; Output:
    VALIDATION_  'GROUP 1'  'GROUP 2'  'GROUP 3'
    15-Nov-2012         42         10          7
    14-Dec-2012         33         32          9It sounds like you're doing real aggregation someplace, to get monthly_count. Maybe it would be simpler and more efficient to do the pivoting at that point. What is the big picture here? Post some sample data as it is before you compute monthly_count, and the results you want from that data (if different from what you've already posted), and then let's see if we can't aggregte it and pivot it at the same time.

  • How to write SQL query and apply aggregate functions on it

    Hello experts,
    Iu2019ve a task to write SQL query on tree tables and do inner join on them. Iu2019ve accomplish this task by using T-CODE SQVI. However now I need to write a query and apply SQL functions on it i.e. Add, Count, Max and Min etc. Please can someone tell me how I can write SQL query with aggregate functions in SAP?
    Thanks a lot in advance

    HI Mr. Cool
    you can see the below code for using aggregate functions.
    where ARTIST and SEATSOCCU are the field names for which you want to perform these functions.
    DATA: TOTAL_ENTRIES TYPE I,
          TOTAL_ATT TYPE I,
          MAX_ATT TYPE I,
          AVG_ATT TYPE I.
    SELECT COUNT( DISTINCT ARTIST )
           SUM( SEATSOCCU )
           MAX( SEATSOCCU )
           AVG( SEATSOCCU ) FROM YCONCERT INTO (TOTAL_ENTRIES, TOTAL_ATT,
    MAX_ATT, AVG_ATT).
    Thanks
    Lalit Gupta

  • Aggregate functions in EJBQL ???

    Does the latest version of Oracle App server support aggregate functions like SUM/COUNT/AVG in the EJBQL?

    Does the latest version of Oracle App server support aggregate functions like SUM/COUNT/AVG in the EJBQL? Hi Swami --
    The latest version of Oracle9iAS - v903 is J2EE 1.3 compatible so it supports all of the EJB 2.0 specification.
    The EJB 2.0 specification lists the following functions for EJBQL:
    String Functions:
    CONCAT(String, String) returns a String
    SUBSTRING(String, start, length) returns a String
    LOCATE(String, String [, start]) returns an int
    LENGTH(String) returns an int
    Arithmetic Functions:
    ABS(number) returns a number (int, float, or double)
    SQRT(double) returns a double
    The latest version of the EJB 2.1 specification which will be part of J2EE 1.4, has added support for aggregate functions like orderby, sum, count, etc.
    11.2.7.2 Aggregate Functions in the SELECT Clause
    The result of an EJB QL query may be the result of an aggregate function applied to a path expression.
    The following aggregate functions can be used in the SELECT clause of an EJB QL query: AVG,
    COUNT, MAX, MIN, SUM.
    We will support these when the EJB 2.1 specification is finalized and we produce our J2EE 1.4 compatible implementation.
    cheers
    -steve-

  • Trying to create a Histogram type/object for aggregate functions

    Hi,
    I am trying to create an aggregate function that will return a histogram
    type.
    It doesn't have to be an object that is returned, I don't mind returning
    a string but I would like to keep the associative array (or something
    else indexed by varchar2) as a static variable between iterations.
    I started out with the SecondMax example in
    http://www.csis.gvsu.edu/GeneralInfo/Oracle/appdev.920/a96595/dci11agg.htm#1004821
    But even seems that even a simpler aggregate function like one strCat
    below (which works) has problems because I get multiple permutations for
    every combination. The natural way to solve this would be to create an
    associative array as a static variable as part of the Histogram (see
    code below). However, apparently Oracle refuses to accept associate
    arrays in this context (PLS-00355 use of pl/sql table not allowed in
    this context).
    If there is no easy way to do the histogram quickly can we at least get
    something like strCat to work in a specific order with a "partition by
    ... order by clause"? It seems that even with "PARALLEL_ENABLE"
    commented out strCat still calls merge for function calls like:
    select hr,qtr, count(tzrwy) rwys,
    noam.strCat(cnt) rwycnt,
    noam.strCat(tzrwy) config,
    sum(cnt) cnt, min(minscore) minscore, max(maxscore) maxscore from
    ordrwys group by hr,qtr
    Not only does this create duplicate entries in the query result like
    "A,B,C" and "A,C,B" it seems that the order in rwycnt and config are not
    always the same so a user can not match the results based on their
    order.
    The difference between my functions and functions like sum and the
    secondMax demonstrated in the documentation is that secondMax does not
    care about the order in which it gets its arguments and does not need to
    maintain an ordered set in order to return the correct results. A good
    example of a built in oracle function that does care about all its
    arguments and probably has to maintain a similar data structure to the
    one I want is the PERCTILE_DISC function. If you can find the code for
    that function (or something like it) and forward a reference to me that
    in itself would be very helpful.
    Thanks,
    K.Dingle
    CREATE OR REPLACE type Histogram as object
    -- TYPE Hist10 IS TABLE OF pls_integer INDEX BY varchar2(10),
    -- retval hist10;
    -- retval number,
    retval noam.const.hist10,
    static function ODCIAggregateInitialize (sctx IN OUT Histogram)
    return number,
    member function ODCIAggregateIterate (self IN OUT Histogram,
    value IN varchar2) return number,
    member function ODCIAggregateTerminate (self IN Histogram,
    returnValue OUT varchar2,
    flags IN number) return number,
    member function ODCIAggregateMerge (self IN OUT Histogram,
    ctx2 IN Histogram) return number
    CREATE OR REPLACE type body Histogram is
    static function ODCIAggregateInitialize(sctx IN OUT Histogram) return
    number is
    begin
    sctx := const.Hist10();
    return ODCIConst.Success;
    end;
    member function ODCIAggregateIterate(self IN OUT Histogram, value IN
    varchar2)
    return number is
    begin
    if self.retval.exist(value)
    then self.retval(value):=self.retval(value)+1;
    else self.retval(value):=1;
    end if;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateTerminate(self IN Histogram,
    returnValue OUT varchar2,
    flags IN number)
    return number is
    begin
    returnValue := self.retval;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateMerge(self IN OUT Histogram,
    ctx2 IN Histogram) return number is
    begin
    i := ctx2.FIRST; -- get subscript of first element
    WHILE i IS NOT NULL LOOP
    if self.retval.exist(ctx2(i))
    then self.retval(i):=self.retval(i)+ctx2.retval(i);
    else self.retval(value):=ctx2.retval(i);
    end if;
    i := ctx2.NEXT(i); -- get subscript of next element
    END LOOP;
    return ODCIConst.Success;
    end;
    end;
    CREATE OR REPLACE type stringCat as object
    retval varchar2(16383), -- concat of all value to now varchar2, --
    highest value seen so far
    static function ODCIAggregateInitialize (sctx IN OUT stringCat)
    return number,
    member function ODCIAggregateIterate (self IN OUT stringCat,
    value IN varchar2) return number,
    member function ODCIAggregateTerminate (self IN stringCat,
    returnValue OUT varchar2,
    flags IN number) return number,
    member function ODCIAggregateMerge (self IN OUT stringCat,
    ctx2 IN stringCat) return number
    CREATE OR REPLACE type body stringCat is
    static function ODCIAggregateInitialize(sctx IN OUT stringCat) return
    number is
    begin
    sctx := stringCat('');
    return ODCIConst.Success;
    end;
    member function ODCIAggregateIterate(self IN OUT stringCat, value IN
    varchar2)
    return number is
    begin
    if self.retval is null
    then self.retval:=value;
    else self.retval:=self.retval || ',' || value;
    end if;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateTerminate(self IN stringCat,
    returnValue OUT varchar2,
    flags IN number)
    return number is
    begin
    returnValue := self.retval;
    return ODCIConst.Success;
    end;
    member function ODCIAggregateMerge(self IN OUT stringCat,
    ctx2 IN stringCat) return number is
    begin
    self.retval := self.retval || ctx2.retval;
    return ODCIConst.Success;
    end;
    end;
    CREATE OR REPLACE FUNCTION StrCat (input varchar2) RETURN varchar2
    -- PARALLEL_ENABLE
    AGGREGATE USING StringCat;

    GraphicsConfiguration is an abstract class. You would need to subclass it. From the line of code you posted, it seems like you are going about things the wrong way. What are you trying to accomplish? Shouldn't this question be posted in the Swing or AWT forum?

  • Issue in pivot while using aggregate functions

    when I use this below query in oracle sql developer
    ------------->select sum(round(8.08/0.54,2)*30) from dual.
    i am getting result as 448.8.it is a correct value
    but i use this below queries in pivot as same like above query i am getting result of doubled value 914.4.
    PIVOT
    SUM(round(ROUND(sellout,2)/6,2)) AS LAST_6_MON_SELL_OUT,
    SUM(ROUND(inventory,2)) AS INVENTORY_INTINS_1,
    Sum(round(ROUND(inventory,2)/round(ROUND(sellout,2)/6,2),2)*30) As Stockperday
    FOR PRODUCT IN (56,78)
    actually i am getting value for SUM(round(ROUND(sellout,2)/6,2)) is 0.54,*SUM(ROUND(inventory,2))* is 8.08 i the above query ,but i am getting wrong value for this aggregate function Sum(round(ROUND(inventory,2)/round(ROUND(sellout,2)/6,2),2)30)* as 914.4.but actual value is 448.8
    why this problem.can anybody explain me.why this problem

    Try ur luck in 'sql plsql thread'
    PL/SQL

  • Why doesn't PIVOT clause work with COLLECT aggregate function in 11g ?

    Hello all !
    I am really puzzled as to what is considered an aggregate function in the context of the PIVOT clause in 11g.
    I have been toying with quite a few things related to collections lately and this arose as an aside :
    CREATE TABLE TEST_COLL
       NODE_ID    VARCHAR2(15 CHAR) NOT NULL,
       NODE_VALUE VARCHAR2(45 CHAR) NOT NULL,
       NODE_LEVEL NUMBER(1)         NOT NULL
    CREATE OR REPLACE TYPE TREE_NODE AS OBJECT
       NODE_KEY  VARCHAR2( 15 CHAR),
       NODE_NAME VARCHAR2(127 CHAR)
    CREATE OR REPLACE TYPE TREE_NODES AS TABLE OF TREE_NODE NOT NULL;At this stage I am sure we all agree that the query
    SELECT NODE_LEVEL,
           CAST(COLLECT(TREE_NODE(NODE_ID, NODE_VALUE)) AS TREE_NODES) AS NODES
      FROM TEST_COLL
    GROUP BY NODE_LEVEL;is perfectly valid as the COLLECT function is an aggregate function according to the [Official Documentation|http://docs.oracle.com/cd/E11882_01/server.112/e10592/functions031.htm#i1271564]
    But then, one of the following two queries should work
    SELECT CAST(REGION_NODES     AS TREE_NODES) AS REGIONS,
           CAST(DEPARTMENT_NODES AS TREE_NODES) AS DEPARTMENTS,
           CAST(AREA_NODES       AS TREE_NODES) AS AREAS,
           CAST(CENTRE_NODES     AS TREE_NODES) AS CENTRES
      FROM (SELECT NODE_LEVEL, TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
              FROM TREE_COLL
    PIVOT (COLLECT(NODE) FOR NODE_LEVEL IN (1 AS REGION_NODES,
                                             2 AS DEPARTMENT_NODES,
                                             3 AS AREA_NODES,
                                             4 AS CENTRE_NODES
    or (better)
    SELECT REGION_NODES     AS REGIONS,
           DEPARTMENT_NODES AS DEPARTMENTS,
           AREA_NODES       AS AREAS,
           CENTRE_NODES     AS CENTRES
      FROM (SELECT NODE_LEVEL, TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
              FROM TREE_COLL
    PIVOT (CAST(COLLECT(NODE) AS TREE_NODES) FOR NODE_LEVEL IN (1 AS REGION_NODES,
                                                                 2 AS DEPARTMENT_NODES,
                                                                 3 AS AREA_NODES,
                                                                 4 AS CENTRE_NODES
           );yet, both fail with
    ORA-56902: expect aggregate function inside pivot operationInvestigating further, I found the same behaviour when using XMLAGG as the aggregate function in the PIVOT clause.
    Is this normal ? And if it is, is there any other way to achieve the result I was anticipating ?
    My version is
    SQL> SELECT BANNER FROM V$VERSION;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
    PL/SQL Release 11.2.0.3.0 - Production
    CORE    11.2.0.3.0      Production
    TNS for 64-bit Windows: Version 11.2.0.3.0 - Production
    NLSRTL Version 11.2.0.3.0 - ProductionThanks in advance
    Best Regards
    Philip

    Most likely a bug. But you can bypass it by using any other aggregate making sure group consists of a single row and apply collect to a pivoted value. Yes, the cost is double aggregation. And also there is another cost - you would need to create MAP member function otherwise aggreations like MAX/MIN, etc. will not work:
    CREATE OR REPLACE TYPE TREE_NODE AS OBJECT
       NODE_KEY  VARCHAR2( 15 CHAR),
       NODE_NAME VARCHAR2(127 CHAR),
       map member function f return varchar2
    Type created.
    CREATE OR REPLACE TYPE BODY TREE_NODE AS
      map member function f return varchar2 is
      begin
         return NODE_NAME;
      end f;
    end;
    Type body created.
    CREATE OR REPLACE TYPE TREE_NODES AS TABLE OF TREE_NODE NOT NULL
    Type created.
    SQL> select  *
      2    from  test_coll
      3  /
    NODE_ID NODE_VALUE NODE_LEVEL
    1       A                   1
    2       B                   2
    3       C                   3
    4       D                   4
    5       E                   1
    6       F                   2
    7       G                   3
    8       H                   4
    8 rows selected.
    SQL> Now:
    SELECT CAST(COLLECT(REGION_NODES)     AS TREE_NODES) AS REGIONS,
           CAST(COLLECT(DEPARTMENT_NODES) AS TREE_NODES) AS DEPARTMENTS,
           CAST(COLLECT(AREA_NODES)       AS TREE_NODES) AS AREAS,
           CAST(COLLECT(CENTRE_NODES)     AS TREE_NODES) AS CENTRES
      FROM (
            SELECT  ROWID RID,
                    NODE_LEVEL,
                    TREE_NODE(NODE_ID, NODE_VALUE) AS NODE
              FROM  TEST_COLL
    PIVOT (MAX(NODE) FOR NODE_LEVEL IN (
                                         1 AS REGION_NODES,
                                         2 AS DEPARTMENT_NODES,
                                         3 AS AREA_NODES,
                                         4 AS CENTRE_NODES
    REGIONS(NODE_KEY, NODE_NAME)                         DEPARTMENTS(NODE_KEY, NODE_NAME)                     AREAS(NODE_KEY, NODE_NAME)                           CENTRES(NODE_KEY, NODE_NAME)
    TREE_NODES(TREE_NODE('1', 'A'), TREE_NODE('5', 'E')) TREE_NODES(TREE_NODE('6', 'F'), TREE_NODE('2', 'B')) TREE_NODES(TREE_NODE('7', 'G'), TREE_NODE('3', 'C')) TREE_NODES(TREE_NODE('8', 'H'), TREE_NODE('4', 'D'))
    SQL> SY.

  • Can't have aggregate function in WHERE clause clause

    Dear all,
    I've created object in BO XI 3.1 Designer with following criterias:
    http://img4.imageshack.us/img4/833/20111201124314.th.jpg
    It is a simple number - 1,2,3,4,5.
    Now I need to use this object as a criteria for WHERE function in another object.
    http://img607.imageshack.us/img607/1543/20111201124717.th.jpg
    I receive an error "Can't have aggregate function in WHERE clause <clause>"
    How can I overcome this?
    P.S. I'm sorry in advance if such topic already exist - I didn't found one.
    Edited by: Ashot Antonyan on Dec 1, 2011 9:50 AM
    Edited by: Ashot Antonyan on Dec 1, 2011 9:51 AM

    Hi,
    You will have to use Sub query to achieve this. Give more details on what is available and what you need then i could help you out with the complete solution.
    Thanks,
    Ravichandra K

Maybe you are looking for

  • How can I use a 3rd party XML parser such as xerces with OC4J ?

    Hi all tech experts, I am using Oracle Application Server 10g Release 2 (10.1.2) and i have installed Portal and Wireless and OracleAS Infrastructure on the same computer. i tried all the solutions on this thread Use of Xerces Parser in out applicati

  • Setting Path variable in Win XP Pro

    Hello, I have installed Java SDK 1.3.0_02 on Windows XP professional. I have set my path to: %SystemRoot%\system32; %SystemRoot%; %SystemRoot%\system32\WBEM; %SystemRoot%; %SystemRoot%\system32\WBEM; C:\Program Files\Common Files\Adaptec Shared\Syste

  • Ipad 2 deleted photo recovery?, Ipad 2 deleted photo recovery?

    I have accidentally deleted a key photo on my I pad 2, I have not switched the device off, I am not connected to I cloud as I am in Eastern Egypt with very limited connection suggestions please, no I cannot take the picture again!

  • Macbook Pro Restore without disk

    Hi everyone, I have a Macbook Pro bought in 2009. I had both OS and Windows XP installed. My friend did something to it and now it just directly boots into XP, and you don't have the choice to delete XP partition in OS Bootcamp (cuz OS doesn't even b

  • Audiobook confusion – no order to how they are listed – cant find anything

    OK I have lots of audio books on my ipod. The only issue is, some of them are ones I have ripped from CD and so they have tons and tons of tracks. At first, the ones I ripped were in the music section of my library and the ones I bought from audible