Aggregate Function in SQL subquery

Hello,
I am trying to use the following syntax and it is saying I can't use an aggregate function in a subquery. I can't use a GROUP BY in this case because if another field in the project table (such as status) is different, that project will show up twice.
So in this case I am using this syntax to show the most recent quote within the project.
SELECT PROJECT.*, QUOTE.QuoteDate, QUOTE.QuoteCode
FROM PROJECT LEFT JOIN QUOTE ON PROJECT.ProjectID = QUOTE.ProjectID
WHERE QUOTE.QuoteDate=(SELECT Max(Q.QuoteDate) FROM QUOTE Q WHERE Q.ProjectID = PROJECT.ProjectID);
My goal here is to show the most recent quote within each project (there can be multiple revisions of a quote within each project). I want to show other fields such as the status of the quote, but if the status is different between quotes, the GROUP BY on that
field will cause it to be listed more than once. All I want to show is the most recent quote for each project.
Let me know if this isn't clear.
Thanks.

Try the below querySELECT P1.projectID,p1.QuoteDate, Q1.QuoteCode,p1.*
FROM PROJECT P1 inner join (SELECT Q.ProjectID,Max(Q.QuoteDate) QD FROM QUOTE Q group by Q.ProjectID) Q1 on Q1.ProjectID = P1.ProjectID and Q1.QD=P1.QuoteDate-Prashanth

Similar Messages

  • 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

  • Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

    I am getting "Cannot perform an aggregate function on an expression containing an aggregate or a subquery." error by executing below query, I need to calculate the percentage. Can you please help me on this by modifying the query.
    select oe2.OrdSourceID,Count(oe2.OrdSourceID) as TotalOrders,
    Percentage = Count(oe2.OrdSourceID) * 100.0 / SUM(Count(oe2.OrdSourceID))
      from OeOrders Oe 
      iNNER JOIN OeOrders2 AS oe2
           ON Oe.OrderID = oe2.OrderID
    where
    Oe.ProviderID = 'JOHN' and Oe.OrderDateTime between '10/07/2014' and '10/15/2014' and oe2.OrdSourceID is not null
      AND Oe.[Status] NOT IN ( 'CANCEL', 'CANC', 'CNC', 'UNVER', 'UNV' )
    Group by oe2.OrdSourceID
    Thanks..
    Diddi

    Hi,
    please check this general solution using CTE. If you need a specific query help then pls post your DDL+DML :-) I hope you can get the idea from this example.
    /************************************************ DDL+DML */
    -- DDL
    create table T (Num int, Name nvarchar(10))
    -- DML
    insert T values (1,'a'),(2,'a'),(3,'s'),(22,'s')
    GO
    /************************************************ Testing and solution */
    select SUM(count(*))
    from T
    GO
    --Msg 130, Level 15, State 1, Line 7
    --Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
    ;with MyCTE as (select count(*) C, Name from T group by Name)
    --select * from MyCTE
    select SUM(C), Name
    from MyCTE
    group by Name
    GO
    /************************************************ Clean */
    drop table T
    GO
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • SQL Aggregate Function

    I am trying to create a query that will output a single row for each employee. Unfortunately, I can't figure out how to group by the aggregate function itself. Is there a way to do this in SQL Developer? Here is my code at this point:
    COL ename FORMAT A25 HEADING Employee|Name
    COL salary FORMAT $999,999.99 HEADING Salary
    COL comm FORMAT A10 HEADING Commission|Rate
    COL earn FORMAT $999,999,999.99 HEADING Sept/2010|Earnings
    SELECT DISTINCT e.last_name||', '||e.first_name "ename",salary,
    CASE WHEN commission_pct > 0 THEN
    commission_pct
    ELSE 0
    END AS comm,
    CASE WHEN commission_pct > 0
    AND o.total > 0 THEN
    (SUM(o.total)*(commission_pct*.01)+salary)
    ELSE salary
    END AS earn
    FROM (SELECT sales_rep_id,total
    FROM s_ord
    WHERE date_ordered LIKE '%SEP-10') o
    RIGHT OUTER JOIN s_emp e
    ON e.id = o.sales_rep_id
    GROUP BY e.last_name,e.first_name,e.salary,e.commission_pct,o.total;

    How do I ask a question on the forums?
    SQL and PL/SQL FAQ
    SELECT DISTINCT e.last_name
                    ||', '
                    ||e.first_name "ename",
                    salary,
                    CASE
                      WHEN commission_pct > 0 THEN commission_pct
                      ELSE 0
                    END            AS comm,
                    CASE
                      WHEN commission_pct > 0
                           AND o.total > 0 THEN ( SUM(o.total) * (
                                                  commission_pct * .01 ) + salary )
                      ELSE salary
                    END            AS earn
    FROM   (SELECT sales_rep_id,
                   total
            FROM   s_ord
            WHERE  date_ordered LIKE '%SEP-10') o
           right outer join s_emp e
                         ON e.id = o.sales_rep_id
    GROUP  BY e.last_name,
              e.first_name,
              e.salary,
              e.commission_pct,
              o.total;

  • PL/SQL : User defined Aggregate Functions ??

    Is it possible to create (using whatever language) a user defined aggregate function for transparent usage within sql ?
    e.g.
    select median(myField) from myTable
    or
    select empirical_expectation(myField) from myTable
    thanx in advance ..
    Tobias Oberstein

    HI,
    U can create a stored proc. (PL/SQL) for this and call as any other function.
    By using external procedure, U can create shared library in C or C++ and coonect this shared library by using external function/procedure. This will be become user-defined procedure.
    with regards,
    Boby Jose Thekkanath.

  • 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

  • OPEN SQL Aggregate Function

    Hi ,
    I want to display no. of invoice by month and yearwise .
    eg.
         JAN     FEB     MAR     APR      .....
    2008      10     15     7     8      ......
    2009     9     87     7     77      ...
    is it any easy way to retirve from RBKP - BUDAT using aggregate Function.
    Thanks,
    Kaleel

    I don't think there is a Agg function, create a Index specfic to BUDAT or check the COPA tables
    -Devendar

  • How to Perform an Aggregate Function?

    Hi,
    I'm trying to define in Designer 6.5 an object with the following select: (example)
    sum (count (distinct REPORTING.table.object_name))
    the SQL parsing restitues me this error --> "The SQL can not perform an aggregate function on an expression containing an aggregate or a subquery".
    Can anyboby explain me the problem and above all how to solve it?
    Thanks
    Riccardo

    Hi,
    You cannot mix different aggregations functions in the same SQL expression: this is a SQL limitation for all databases.
    You need to use subselect to achieve your requirement.
    See the following example that works on SQL Server:
    Select sum(a._count) from
    (Select count (distinct cust_id) as _count from Club.dbo.Customer) a
    Regards,
    Didier

  • Analitical functions in recursive subquery factoring

    Hi,
    I have a problem with analitical functions in recursive subquery factoring.
    My version:
    >
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
    PL/SQL Release 11.2.0.1.0 - Production
    CORE     11.2.0.1.0     Production
    TNS for 64-bit Windows: Version 11.2.0.1.0 - Production
    NLSRTL Version 11.2.0.1.0 - Production
    >
    When I run following query it runs fine:
    with a (num, total) as
    (select
      1 num
      ,1 total
    from
      dual
    union all
    select
      num + 1             num
      ,total + num + 1    total
    from
      a
    where
      num < 10
    select
    from
      a
    NUM TOTAL
      1     1
      2     3
      3     6
      4    10
      5    15
      6    21
      7    28
      8    36
      9    45
    10    55
    10 rows selected When I run the following query it generates an error:
    with a (num, total) as
    (select
      1 num
      ,1 total
    from
      dual
    union all
    select
      num + 1             num
      ,sum(num) over ()    total
    from
      a
    where
      num < 10
    select
    from
      a
    Error:
    ORA-32486: unsupported operation in recursive branch of recursive WITH clause The manual states:
    >
    Oracle® Database
    SQL Language Reference
    11g Release 2 (11.2)
    E17118-04
    October 2010
    The recursive member cannot contain any of the following elements:
    - The DISTINCT keyword or a GROUP BY clause
    - The model_clause
    - An aggregate function. However, analytic functions are permitted in the select list.
    - Subqueries that refer to query_name.
    - Outer joins that refer to query_name as the right table.
    >
    According to this it should be posible to have an analitical function in here.
    Also on this form I see samples of it used as such.
    eg.:
    Re: Seat Distribution-Can we do this in SQL?
    Can anybody tell me if this is a problem with my version of oracle?
    Or is there some other problem here?
    Thanks,
    Peter

    Works ok in 11.2.0.3
    SQL> select * 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 - Production
    SQL> with a (num, total) as
      2  (select
      3    1 num
      4    ,1 total
      5  from
      6    dual
      7  union all
      8  select
      9    num + 1             num
    10    ,sum(num) over ()    total
    11  from
    12    a
    13  where
    14    num < 10
    15  )
    16  select
    17    *
    18  from
    19    a
    20  ;
           NUM      TOTAL
             1          1
             2          1
             3          2
             4          3
             5          4
             6          5
             7          6
             8          7
             9          8
            10          9
    10 rows selected.

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

  • 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

  • A function in a subquery is call too many times.

    Dear all,
    I'm struggling to understand why a function in a subquery is called too many times.
    Let me explain with an example:
    create or replace function all_emp (v_deptno in number)
    return varchar2
    as
    v_all_emp varchar2(2000);
    begin
        dbms_output.put_line ('function called');
        for i in (select * from emp where deptno = v_deptno) loop
            v_all_emp := v_all_emp || i.ename || '; ';
        end loop;
    return v_all_emp;
    end;
    -- running just the subquery, calls the function all_emp only 4 times (once for each row in table dept)
    select
        d.deptno,
        d.dname,
        all_emp(d.deptno) f_all_emp
        from dept d;
    -- running the whole query, using regexp to split the value of f_all_emp into separate fields, causes that function all_emp is called 28 times, thus 6 times for each row!!
    select tmp.*,
    regexp_substr(f_all_emp,'[^;]*',1,1) emp1,
    regexp_substr(f_all_emp,'[^;]*',1,3) emp2,
    regexp_substr(f_all_emp,'[^;]*',1,5) emp3,
    regexp_substr(f_all_emp,'[^;]*',1,7) emp4,
    regexp_substr(f_all_emp,'[^;]*',1,9) emp5,
    regexp_substr(f_all_emp,'[^;]*',1,11) emp6
    from
        (select
        d.deptno,
        d.dname,
        all_emp(d.deptno) f_all_emp
        from dept d) tmp
    ;I don't understand why Oracle is calling my function 28 times in this example, 4 times should be sufficient.
    Is there a way to force that the subquery is materialized first?
    Little background:
    Above function / query is of course a simple example.
    Actually I have pretty complex function, embedding in a subquery.
    The subquery is already slow (2 min to run), but when I want to split the result of the funciton in multiple (approx 20) fields it's over an hour due to above described behaviour.

    Optimizer merges in-line view and query results in:
    select  d.deptno,
            d.dname,
            all_emp(d.deptno) f_all_emp
            regexp_substr(all_emp(d.deptno),'[^;]*',1,1) emp1,
            regexp_substr(all_emp(d.deptno),'[^;]*',1,3) emp2,
            regexp_substr(all_emp(d.deptno),'[^;]*',1,5) emp3,
            regexp_substr(all_emp(d.deptno),'[^;]*',1,7) emp4,
            regexp_substr(all_emp(d.deptno),'[^;]*',1,9) emp5,
            regexp_substr(all_emp(d.deptno),'[^;]*',1,11) emp6
      from  dept d
    /That's why function is called 28 times. We can see it from explain plan:
    SQL> explain plan for
      2  select tmp.*,
      3          regexp_substr(f_all_emp,'[^;]*',1,1) emp1,
      4          regexp_substr(f_all_emp,'[^;]*',1,3) emp2,
      5          regexp_substr(f_all_emp,'[^;]*',1,5) emp3,
      6          regexp_substr(f_all_emp,'[^;]*',1,7) emp4,
      7          regexp_substr(f_all_emp,'[^;]*',1,9) emp5,
      8          regexp_substr(f_all_emp,'[^;]*',1,11) emp6
      9    from  (
    10           select  d.deptno,
    11                   d.dname,
    12                   all_emp(d.deptno) f_all_emp
    13             from  dept d
    14          ) tmp
    15  /
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 3383998547
    | Id  | Operation         | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT  |      |     4 |    52 |     3   (0)| 00:00:01 |
    |   1 |  TABLE ACCESS FULL| DEPT |     4 |    52 |     3   (0)| 00:00:01 |
    8 rows selected.
    SQL>  If we use NO_MERGE hint:
    SQL> select  /*+ NO_MERGE(tmp) */
      2          tmp.*,
      3          regexp_substr(f_all_emp,'[^;]*',1,1) emp1,
      4          regexp_substr(f_all_emp,'[^;]*',1,3) emp2,
      5          regexp_substr(f_all_emp,'[^;]*',1,5) emp3,
      6          regexp_substr(f_all_emp,'[^;]*',1,7) emp4,
      7          regexp_substr(f_all_emp,'[^;]*',1,9) emp5,
      8          regexp_substr(f_all_emp,'[^;]*',1,11) emp6
      9    from  (
    10           select  d.deptno,
    11                   d.dname,
    12                   all_emp(d.deptno) f_all_emp
    13             from  dept d
    14          ) tmp
    15  /
        DEPTNO DNAME          F_ALL_EMP  EMP1       EMP2       EMP3       EMP4       EMP5       EMP6
            10 ACCOUNTING     CLARK; KIN CLARK       KING       MILLER
                              G; MILLER;
            20 RESEARCH       SMITH; JON SMITH       JONES      SCOTT      ADAMS      FORD
                              ES; SCOTT;
                               ADAMS; FO
                              RD;
            30 SALES          ALLEN; WAR ALLEN       WARD       MARTIN     BLAKE      TURNER     JAMES
                              D; MARTIN;
        DEPTNO DNAME          F_ALL_EMP  EMP1       EMP2       EMP3       EMP4       EMP5       EMP6
                               BLAKE; TU
                              RNER; JAME
                              S;
            40 OPERATIONS
    function called
    function called
    function called
    function called
    function called
    function called
    SQL> explain plan for
      2  select  /*+ NO_MERGE(tmp) */
      3          tmp.*,
      4          regexp_substr(f_all_emp,'[^;]*',1,1) emp1,
      5          regexp_substr(f_all_emp,'[^;]*',1,3) emp2,
      6          regexp_substr(f_all_emp,'[^;]*',1,5) emp3,
      7          regexp_substr(f_all_emp,'[^;]*',1,7) emp4,
      8          regexp_substr(f_all_emp,'[^;]*',1,9) emp5,
      9          regexp_substr(f_all_emp,'[^;]*',1,11) emp6
    10    from  (
    11           select  d.deptno,
    12                   d.dname,
    13                   all_emp(d.deptno) f_all_emp
    14             from  dept d
    15          ) tmp
    16  /
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 2317111044
    | Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT   |      |     4 |  8096 |     3   (0)| 00:00:01 |
    |   1 |  VIEW              |      |     4 |  8096 |     3   (0)| 00:00:01 |
    |   2 |   TABLE ACCESS FULL| DEPT |     4 |    52 |     3   (0)| 00:00:01 |
    9 rows selected.
    SQL> Not sure why function is executed 6 and not 4 times. What we actually want is to materialize in-line view:
    SQL> with tmp as (
      2               select  /*+ materialize */
      3                       d.deptno,
      4                       d.dname,
      5                       all_emp(d.deptno) f_all_emp
      6                 from  dept d
      7              )
      8  select  tmp.*,
      9          regexp_substr(f_all_emp,'[^;]*',1,1) emp1,
    10          regexp_substr(f_all_emp,'[^;]*',1,3) emp2,
    11          regexp_substr(f_all_emp,'[^;]*',1,5) emp3,
    12          regexp_substr(f_all_emp,'[^;]*',1,7) emp4,
    13          regexp_substr(f_all_emp,'[^;]*',1,9) emp5,
    14          regexp_substr(f_all_emp,'[^;]*',1,11) emp6
    15    from  tmp
    16  /
        DEPTNO DNAME          F_ALL_EMP  EMP1       EMP2       EMP3       EMP4       EMP5       EMP6
            10 ACCOUNTING     CLARK; KIN CLARK       KING       MILLER
                              G; MILLER;
            20 RESEARCH       SMITH; JON SMITH       JONES      SCOTT      ADAMS      FORD
                              ES; SCOTT;
                               ADAMS; FO
                              RD;
            30 SALES          ALLEN; WAR ALLEN       WARD       MARTIN     BLAKE      TURNER     JAMES
                              D; MARTIN;
        DEPTNO DNAME          F_ALL_EMP  EMP1       EMP2       EMP3       EMP4       EMP5       EMP6
                               BLAKE; TU
                              RNER; JAME
                              S;
            40 OPERATIONS
    function called
    function called
    function called
    function called
    SQL> explain plan for
      2  with tmp as (
      3               select  /*+ materialize */
      4                       d.deptno,
      5                       d.dname,
      6                       all_emp(d.deptno) f_all_emp
      7                 from  dept d
      8              )
      9  select  tmp.*,
    10          regexp_substr(f_all_emp,'[^;]*',1,1) emp1,
    11          regexp_substr(f_all_emp,'[^;]*',1,3) emp2,
    12          regexp_substr(f_all_emp,'[^;]*',1,5) emp3,
    13          regexp_substr(f_all_emp,'[^;]*',1,7) emp4,
    14          regexp_substr(f_all_emp,'[^;]*',1,9) emp5,
    15          regexp_substr(f_all_emp,'[^;]*',1,11) emp6
    16    from  tmp
    17  /
    Explained.
    SQL> @?\rdbms\admin\utlxpls
    PLAN_TABLE_OUTPUT
    Plan hash value: 634594723
    | Id  | Operation                  | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT           |                            |     4 |  8096 |     5   (0)| 00:00:01 |
    |   1 |  TEMP TABLE TRANSFORMATION |                            |       |       |            |          |
    |   2 |   LOAD AS SELECT           |                            |       |       |            |          |
    |   3 |    TABLE ACCESS FULL       | DEPT                       |     4 |    52 |     3   (0)| 00:00:01 |
    |   4 |   VIEW                     |                            |     4 |  8096 |     2   (0)| 00:00:01 |
    |   5 |    TABLE ACCESS FULL       | SYS_TEMP_0FD9D6603_20255AE |     4 |    52 |     2   (0)| 00:00:01 |
    PLAN_TABLE_OUTPUT
    12 rows selected.
    SQL> However, hint MATERIALIZE is an undocumented hint.
    SY.

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

  • How can I use User-Defined Aggregate Functions in Timesten 11? such as ODCI

    Hi
    we are using Timesten 11 version and as per the documentation, it doesn't support User-Defined Aggregate Functions.
    So we are looking for alternatives to do it. Could you please provide your expert voice on this.
    Thanks a lot.
    As the following:
    create or replace type strcat_type as object (
    cat_string varchar2(32767),
    static function ODCIAggregateInitialize(cs_ctx In Out strcat_type) return number,
    member function ODCIAggregateIterate(self In Out strcat_type,value in varchar2) return number,
    member function ODCIAggregateMerge(self In Out strcat_type,ctx2 In Out strcat_type) return number,
    member function ODCIAggregateTerminate(self In Out strcat_type,returnValue Out varchar2,flags in number) return
    number
    How can I use User-Defined Aggregate Functions in Timesten 11? such as ODCIAggregateInitialize ?

    Dear user6258915,
    You absolutely right, TimesTen doesnt support object types (http://docs.oracle.com/cd/E13085_01/doc/timesten.1121/e13076/plsqldiffs.htm) and User-Defined Aggregate Functions.
    Is it crucial for your application? Could you rewrite this functionality by using standart SQL or PL/SQL?
    Best regards,
    Gennady

Maybe you are looking for