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;

Similar Messages

  • 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

  • SQL Aggregate function and Subquery issues

    Hello,
    I'm trying to create an SQL statement that gives the rate of all Urgent surgeries Grouped by sector (i.e Surgery, Radiology), and Fiscal year
    To do this I need to divide the sum of surgeries with a state "Urgent" by the total surgeries
    In order to pull all the Total surgeries I would need to exclude the surgeries with the state "Cancelled", AND make sure to get rid of duplicates a single surgery may have.
    So this is what I came up with, but I'm not able to apply the following formula in SQL for the rate of Urgent surgeries:
    TOTAL OF URGENT SURGERIES / TOTAL SURGERIES
    Note that the Select statement within the WITH CLAUSE runs successfully when running it separately
    With T1 As(
    SELECT                          
    b."etat",                         
    c."secteur",                    
    d.annee_fiscale_full,                         
    d.periode,
    SUM(Count(distinct b."Cle_requete")) OVER (PARTITION BY b."etat", c."secteur", d.annee_fiscale_full, d.periode) AS TOTAL_SURGERIES
    FROM vsRequete a,                         
    vsEtats b,                         
    vsOperation c,                         
    periode_financiere d,                         
    vstemps_operatoires e                         
    WHERE b."etat" <> 'Cancelled'
    AND (b."Cle_requete" = a."Cle_vsRequete")                         
    AND (c."Cle_requete" = a."Cle_vsRequete")                         
    AND (b."Cle_requete" = c."Cle_requete")                         
    AND (a."Cle_vsRequete" = e."Cle_requete")                         
    AND c."date_operation" = d.per_fina_date                         
    GROUP BY                          
    b."etat",                         
    c."secteur",
    --a."type_visite",
    d.annee_fiscale_full,                         
    d.periode )
    SELECT
    ---- ***NOTE***: SHOULD I BE USING THE FOLLOWING ANALYTIC FUNCTION FOR THE RATE OF URGENT SURGERIES
    ---- RATIO_TO_REPORT(T1.TOTAL_SURGERIES) OVER () As URGENT_SURGERY_RATE,
    T1."secteur",                    
    --a."type_visite",
    T1.annee_fiscale_full,                         
    T1.periode
    FROM T1
    Where T1."etat" = 'Urgent'
    ORDER BY
    T1.annee_fiscale_full,                         
    T1.periode,                    
    T1."secteur";
    Thanks for your help
    Edited by: Ruben_920841 on Dec 21, 2012 1:40 PM
    Edited by: Ruben_920841 on Dec 21, 2012 1:41 PM

    Hi,
    Whenever you have a problem, please post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) from all tables involved.
    Also post the results you want from that data, and an explanation of how you get those results from that data, with specific examples.
    Always say which version of Oracle you're using (for example, 11.2.0.2.0).
    See the forum FAQ {message:id=9360002}
    Ruben_920841 wrote:
    Hello,
    I'm trying to create an SQL statement that gives the rate of all Urgent surgeries Grouped by sector (i.e Surgery, Radiology), and Fiscal year
    To do this I need to divide the sum of surgeries with a state "Urgent" by the total surgeries
    In order to pull all the Total surgeries I would need to exclude the surgeries with the state "Cancelled", AND make sure to get rid of duplicates a single surgery may have.
    So this is what I came up with, but I'm not able to apply the following formula in SQL for the rate of Urgent surgeries:
    TOTAL OF URGENT SURGERIES / TOTAL SURGERIES
    Note that the Select statement within the WITH CLAUSE runs successfully when running it separately
    With T1 As(
    SELECT                          
    b."etat",                         
    c."secteur",                    
    d.annee_fiscale_full,                         
    d.periode,
    SUM(Count(distinct b."Cle_requete")) OVER (PARTITION BY b."etat", c."secteur", d.annee_fiscale_full, d.periode) AS TOTAL_SURGERIES Is it possible, in a group of rows with the same "Cle_requete", for some rows to have "etate"='Urgent' and other rows to have some other value besides 'Cancelled'? If so, how is that counted? Include an example or two in your sample data and results.
    FROM vsRequete a,                         
    vsEtats b,                         
    vsOperation c,                         
    periode_financiere d,                         
    vstemps_operatoires e                         
    WHERE b."etat" <> 'Cancelled'This site doesn't like to display the &lt;&gt; inequality operator. Always use the other (equivalent) inequality operator, !=, when posting here.
    AND (b."Cle_requete" = a."Cle_vsRequete")                         
    AND (c."Cle_requete" = a."Cle_vsRequete")                         
    AND (b."Cle_requete" = c."Cle_requete")                         
    AND (a."Cle_vsRequete" = e."Cle_requete")                         
    AND c."date_operation" = d.per_fina_date                         
    GROUP BY                          
    b."etat",                         
    c."secteur",
    --a."type_visite",
    d.annee_fiscale_full,                         
    d.periode )
    Select
    ----- ***NOTE***: SHOULD I BE USING THE FOLLOWING ANALYTIC FUNCTION FOR THE RATE OF URGENT SURGERIES
    ------ RATIO_TO_REPORT(T1.TOTAL_SURGERIES) OVER () As URGENT_SURGERY_RATE,That depends on your data, and your desired results. Based on what you've said so far, I think not. It's more likely that you'll want to use a CASE expression to get a count of the 'Urgent' surgeries.
    T1."secteur",                    
    --a."type_visite",
    T1.annee_fiscale_full,                         
    T1.periode
    FROM T1
    Where T1."etat" = 'Urgent'
    ORDER BY
    T1.annee_fiscale_full,                         
    T1.periode,                    
    T1."secteur";The forum FAQ {message:id=9360002} explains how to use \ tags to preserve spacing when you post formatted text, such as your query.
    It sounds like your problem is similar to this one:
    "What percentage of the employees (not counting SALESMEN)  in each department of the scott.emp table are CLERKS?"
    Here's one way you might answer that:WITH     got_cnts     AS
         SELECT     deptno
         ,     COUNT ( DISTINCT CASE
                             WHEN job = 'CLERK'
                             THEN ename
                        END
                   )               AS clerk_cnt
         ,     COUNT (DISTINCT ename)     AS total_cnt
         FROM     scott.emp
         WHERE     job     != 'SALESMAN'
         GROUP BY deptno
    SELECT     deptno
    ,     clerk_cnt
    ,     total_cnt
    ,     100 * clerk_cnt
         / total_cnt     AS clerk_pct
    FROM     got_cnts
    ORDER BY deptno
    Output:DEPTNO CLERK_CNT TOTAL_CNT CLERK_PCT
    10 1 3 33.33
    20 2 5 40.00
    30 1 2 50.00

  • Last & First SQL aggregate functions

    I'm trying to migrate an app. from Access to SQL Server, and find that Transact-SQL does not support LAST/FIRST functions.  Is there any alternative to these?
    Below is the Access SQL statement:
    SELECT Last(tblZoneNameString.Val) AS strZoneName, tblZoneNameString.TagIndex
    FROM tblZoneNameString
    GROUP BY tblZoneNameString.TagIndex
    HAVING (((tblZoneNameString.TagIndex)>0));

    In SQL Server 2005, you can do something like this:
    select
    tblZoneNameString.Val as strZoneName,
    tblZoneNameString.TagIndex
    from (
    select
    tblZoneNameString.Val as strZoneName,
    tblZoneNameString.TagIndex,
    rank() over (partition by tblZoneNameString.TagIndex order by ??????) as rk
    from tblZoneNameString
    ) as T
    where rk = 1
    Where I've written ?????? you will need to put whatever column
    or columns answer the question "last in order of what?". Perhaps
    this is something like someDateTime DESC.
    Steve Kass
    Drew University
    [email protected] wrote:
    > I'm trying to migrate an app. from Access to SQL Server, and find that
    > Transact-SQL does not support LAST/FIRST functions. Is there any
    > alternative to these?
    >
    > Below is the Access SQL statement:
    >
    > SELECT Last(tblZoneNameString.Val) AS strZoneName,
    > tblZoneNameString.TagIndex
    > FROM tblZoneNameString
    > GROUP BY tblZoneNameString.TagIndex
    > HAVING (((tblZoneNameString.TagIndex)>0));
    >
    >

  • 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

  • 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

  • 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

  • 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

  • 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

  • Using Aggregate function in queries

    Hi all,
              Please take a look on this query and suggest me why i'm getting the error..
    This is my simple query using aggregate function in it..
    SELECT T1.NAME, T1.DESCRIPTION, SUM(T2.QUANTITY)
    FROM TABLE1 T1, TABLE2 T2
    WHERE T1.ID=T2.ID
    GROUP BY T1.NAME, T1.DESCRIPTION
    Above query added with a sub-query in the select segment..
    SELECT T1.NAME, T1.DESCRIPTION, SUM(T2.QUANTITY), (SELECT AVG(T3.PRICE) FROM TABLE1 TT1, TABLE3 T3 WHERE TT1.ID=T3.ID AND TT1.ID=T1.ID) AV_PRICE
    FROM TABLE1 T1, TABLE2 T2
    WHERE T1.ID=T2.ID
    GROUP BY T1.NAME, T1.DESCRIPTION
    When i add a sub-query which has aggregate function in it, i'm getting the 'ORA-00979: not a GROUP BY expression' error.

    What is your DB Version. Your query works without any issue in my DB. I used WITH clause to create the sample data. The query highlighted in BLUE is the actual query.
    SQL> select * from v$version where rownum = 1;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.5.0 - 64bi
    SQL> with table1
      2  as
      3  (
      4    select 1 id, 'karthick' name, 'user name' description from dual
      5  ),
      6  table2
      7  as
      8  (
      9    select 1 id, 100 quantity from dual
    10  ),
    11  table3
    12  as
    13  (
    14    select 1 id, 10 price from dual
    15  )
    16  select t1.name
    17       , t1.description
    18       , sum(t2.quantity)
    19       , (
    20           select avg(t3.price)
    21             from table1 tt1
    22                , table3 t3
    23            where tt1.id = t3.id
    24              and tt1.id = t1.id
    25         ) av_price
    26    from table1 t1
    27       , table2 t2
    28   where t1.id = t2.id
    29   group
    30      by t1.name
    31       , t1.description;
    NAME     DESCRIPTI SUM(T2.QUANTITY)   AV_PRICE
    karthick user name              100         10
    SQL>

  • Query of queries disallows SQL right() function

    We're attempting to do a query of queries using the SQL
    right() function like this:
    select *
    from getresults
    where right([key],charindex('\',reverse([key]),1)-1) not in
    (#quotedvaluelist(getexcluded.file_name)#)
    We've even replaced that where clause with a much more simple
    where right([key])='m'
    just to make sure that it wasn't the nesting functions that
    were causing the problem.
    In either case, we get the error:
    Query of Queries syntax error.
    Encountered "right" at line 0, column 0. Incorrect
    conditional expression,
    Expected one of [like|null|between|in|comparison] condition,
    What SQL functions are disallowed from query of queries?
    Thanks,
    Kris

    Nasty stuff huh. Just happened to discover myself today that
    Left doesn't work. I'd suspect that Aggregate functions are the
    ONLY ones that will work. It would have been nice if they'd at
    least allowed CF vs DB functions in their own "database" language.
    BTW, also discovered that Count() returns Null rather than 0
    when there aren't any per your WHERE clause.

Maybe you are looking for

  • S_ALR_87013019 -List: Budget/Actual/Commitments Report Error

    Dear All I would like to bring your kind information that while executing the SAP standard T.code: S_ALR_87013019 - List:Budget/Actual/Commitments,we are not able to get the report based on the year wise. As in the SAP release 4.7, when we run the sa

  • I need to convert few pages of a large pdf files, insert a signature then send as an email.

    Is this possible with this product?  I'm  not having much luck so far... What are the steps to convert pdf files in the first place?  I get them via email so do I: First download the whoe pdf file then upload it to ExportPDF, then convert it to Word

  • Created by (submitted by) varaible

    I would like to include the created (submitted) by variable in the change management email notification. Does anyone know if this possible – I am noob to service manager so any help would be great.

  • Using PKI to secure our infrastructure

    Hi, We have 300 employees in our organization and now we'd like to provide them new services, but keep their devices under our control. Main questions are: - due work activities and our job structure, a lot of employees are working at home. Some of t

  • Cs3 and cs4 web standard compatible with vista home basic?

    Are Adobe CS3 and CS4 Web Standard compatible with Vista Home Basic 32bit? I only see Windows Vista Home Premium / Vista Business / Vista Enterprise / Vista Ultimate / XP listed as compatible. Many thanks.