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

Similar Messages

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

  • Aggregate functions and normal function in SELECT statement

    hi
    i am using MS Access DataBase ...
    i have lot of integer coloumns in my Database
    i want to retrieve the coloumn values as well as the min , max and avg of that coloumn
    i dont know whether its possible to do in a single statement or not
    generally if we retrieve the values of a particular coloum
    we say " SELECT length FROM TABLENAME WHERE somecondition"
    and then get the values as int len = rs.getInt("length")..... over a loop
    but how to retieve the value of an aggregate function?
    like if i say "SELECT avg(colname),max(colname),min(colname) FROM TABLENAME WHERE somecondition"
    how do i retrieve this value ???
    i dont know if its possible or not ....pls help.........

    Give names too each column
    SELECT avg(colname) average,max(colname) max,....
    and then rs.getInt("average")
    This works in Oracle and Sybase, not sure on MS access tough

  • Running SQL Server Function and Procedures from Oracle

    I am trying to run SQL Server 2005 functions and/or procedures from a SQL statement in Oracle. I have gone throught the hetergeneous services and have connected to the SQL Server database successfully. I can also do a query to a table in SQL Server successfully; but I have not been able to execute a procedure or a function.

    Have you tried Oracle syntax? It seems to me that you have only tried T-SQL syntax, e.g. execute proc.
    Wrap it in a begin..end tag like you would a normal PL/SQL function or proc call. Assumption is that as Oracle makes the remote database (via the dblink) look like an Oracle database, you should also play along and pretend it is one and treat it as such.
    E.g.declare
      r integer;
    begin
      -- execute remote proc
      procFoo@dblink( 'ABC' );
      -- call a remote function
      r := funcFoo@dblink( 123 );
    end;

  • Database Aggregate Functions and Oracle Discoverer

    Hello Guys.
    There are a lot of aggregate function inside the database, unfortunatelly some of them are not directly accesible from Oracle Discoverer.
    For example :
    STATS_BINOMIAL_TEST
    STATS_CROSSTAB
    STATS_F_TEST
    STATS_KS_TEST
    STATS_MODE
    STATS_MW_TEST
    STATS_ONE_WAY_ANOVA
    STATS_T_TEST_*
    STATS_WSR_TEST
    What is the best way to incorporate this kind of function in Oracle Discoverer ?
    Thanks
    Ramiro Ortiz Rios

    While Discoverer today is unable to recognize these Oracle Database functions, we are looking at adding this capability into the product. If you think this is important, please take the poll at http://oraclebi.blogspot.com/2006/04/must-have-in-discoverer.html
    Also, if you can spare a few minutes, do send me a mail at abhinav.oracle at gmail.com with a brief description of a use case that describes where and how these functions would be used.
    Thanks
    Abhinav
    Oracle Business Intelligence Product Management
    BI on Oracle: http://www.oracle.com/bi/
    BI on OTN: http://www.oracle.com/technology/products/bi/
    Documentation: http://docs.oracle.com/
    Oracle BI Suite EE: http://www.oracle.com/technology/products/bi/enterprise-edition.html
    Oracle BI Suite SE: http://www.oracle.com/technology/products/bi/standard-edition.html
    Oracle BI Suite SE One: http://www.oracle.com/technology/products/bi/standard-edition-one.html
    Discoverer: http://www.oracle.com/technology/products/discoverer/
    BI Software: http://www.oracle.com/technology/software/products/ias/devuse.html
    BI Blog: http://oraclebi.blogspot.com/
    Blogs: http://blogs.oracle.com/

  • Selecting both a aggregate function and another field

    I am trying to do something very simple but I am not sure of the syntax.
    I would like to select all of the petid's and find the count of the pets in a given city, both from the same table, Pets.
    Can somebody please help me with this?
    Thanks

    Hi,
    An aggregate function will give you one row of output per group.
    For example, if you use the aggregate COUNT function to get the total number of rows in a whole table, then you can only have one row of output, representing the whole table, so, if I understand the problem, you can't (easily) use an aggregate function.
    Almost all of the aggregate functions have analytic counterparts, that can produce the same results without collapsing the result set into one row per group.
    I think this is what you requested:
    SELECT  petid
    ,       COUNT (*) OVER (PARTITION BY 1)  AS total_cnt
    FROM    pets
    WHERE   city    = 'Paris'  -- or whatever
    ;Sorry, I'm not at a database now, so I can't check, but I think you don't need the PARTITION BY clause, so you can also say:
    ,       COUNT (*) OVER ()  AS total_cntThe keyword OVER marks this as an analytic, rather than an aggregate, function.

  • 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

  • PDK pl/sql add_item function and documents table

    When we use the add_item function to add an item and upload its content, does the add_item function uploads document content to the document table in the repository?(like the upload_blob() function)
    If yes, can I remove the uploaded document from the filesystem after having uploaded it in the documents table?
    The PDK API says that there is no supported view for querying the document table. Is there any other way to query the documents in the document table? Or any additional information about how the documents are stored in the document table or how the documents table works?

    Duplicate thread ->
    PL/SQL add procedure with nested table
    Please remove it & marked it as duplicate.
    Regards.
    Satyaki De.

  • Compiling Packages, Functions, and Procedures Issues

    If you are in the editor for a package and attempt to compile a know good package under another schema (compiled in SQL+ and Toad), you receive the following errors:
    Error(21,5): PLW-06002: Unreachable code
    Error(131,7): PLW-07202: bind type would result in conversion away from column type
    (122) TN_EXISTS NUMBER := 0;
    (131) IF TN_EXISTS > 0 THEN ...
    When commenting a line with if you have something like the following it tells you there is a syntax error
    -- some comment here --
    When compiling a PL/SQL function that returns a Boolean, you get this error: Error(40,4): PLW-06002: Unreachable code

    Kris,
    I seem to have the same problem.
    Is there a way to 'deactivate' this behaviour, or do we need to wait for another Raport Release.
    This is basically preventing me from using Raptor at all for any PL/SQL development ;-(
    Wouter

  • Aggregate Functions and Difference

    I had posted this question earlierRCOUNT and RSUM but if that was too many details, let me simplify it here.
    Month_Number -----Count(Orders)----------Increase In Sales
    1-------------------------100------------------------- -
    2-------------------------400------------------------- 300
    3-------------------------280------------------------- -20
    This is what Im looking for. As I have to use the Count() I am using Group By on Month_Number.
    RSUM didn't work in this case. Any solution to get this working ?
    Thanks
    Edited by: user558238 on Jan 19, 2009 11:06 PM

    As you have only one period in the difference.
    For instance :
    Month 2 - Month 1
    and not
    Month 3 - Month 1
    You can use this formula :
    MSUM (CountOrders, 2) - 2 * CountOrdersIt calculate a moving sum on 2 periods and subtract 2 sum of the current period.
    Otherwise, you can use the Time function series (AGO, TODATE) but it's only possible in the repository layer and not in the Business presentation layer :
    http://gerardnico.com/wiki/dat/obiee/bi_server/design/dimension/time_dimension_parameters_for_ago_and_td_functions
    AGO(CountOrders, SH.TimesDim."Month", 1)An other solution will be the use of a sql function.
    Success
    Nico

  • 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));
    >
    >

  • Run function and Scene issue

    I am new to javafx and this is my first program in general in a couple years...now that the disclaimer is out of the way here goes:
    I am calling my javafx program from a java client and I am having trouble with the javafx scene being displayed. I have the following code:
    function run(){
         ...var declarations from java client...
    var design = MediaPlayer {};
    design.setItems();
    keepTime = design.getKT();
    javafx.stage.Stage {
    title: "MEDIA PLAYER"
    scene: design.getDesignScene ()
    I have added some print outs in the past and it appears that the run function is called fine, but once I reach the code "design.setItems()" it does not appear to go any further. I have try and catch around everything for an exception, but I get nothing. I have the run function declared outside of my MediaPlayer class and I am trying to understand that whole concept of code outside of the class within the file.
    some other things to note: I am making the javafx call on a new thread created in my java code. when I close my java window then the javafx code seems to proceed past "design.setItems()" and the scene displays and everything is fine thereafter...oh, except that I had to close my java program...weird.
    I have tried putting the run function within the class, but the nothing seems to happen at all then.
    Ideas? Question?

    The javafx doesn't have main method as Java has.
    So javafx has provided the function run() to execute the program. If you put the function run on your any class suppose 'A' then while calling the Class 'A' like : A{} in javafx then it would directly run your function run() and make the object too. But when you want only the object to be loaded then you would better not to include function run() on your class.
    For variables,
    the variable declared on function run is only accessible for function run . It's totally private to others.
    Thanks,
    narayan

  • Aggregate function and join

    I have three Tables(Emptimesheet,comexpensetable,perexpensestable).I want to show otput something like below,
    EmpID,EmpName,StartDate,EndDate,Total,Chotel,CAirfare,Cfuel,WeeklCompanyExpenses,Percompanyexpenses
    rightnow in the below query I don't have hotel,airfare,fuel.
    select distinct(e.EmpID) ,e.EmpName, e.StartDate,e.EndDate,e.Total,c.WeeklyComtotalExpenses,p.WeeklyPerTotalExpenses
    from EmpTimeSheet e left JOIN ComExpensesTable c on c.CExpID=e.EmpID left join PerExpensesTable p ON p.PExpID=e.EmpID
    Output for Above query .
    EmpID name sd ED Total companEx PerExpense 1 tom 2014-02-02 00:00:00.000 2014-02-08 00:00:00.000 28:30:0 213.00 199.00
    3 nick 2014-03-02 00:00:00.000 2014-03-08 00:00:00.000 15:20:0 16.00 NULL
    4 john 2014-03-23 00:00:00.000 2014-03-29 00:00:00.000 42:0:0 NULL NULL
    5 test 2014-03-09 00:00:00.000 2014-03-15 00:00:00.000 34:15:0 NULL NULL
    6 ema 2014-04-13 00:00:00.000 2014-04-19 00:00:00.000 39:0:0 16.00 NULL
    Output  Emptimesheet
    id empname startdate enddate .. total 1 tom 2014-02-02 00:00:00.000 2014-02-08 00:00:00.000 Thurs 2014-02-06 00:00:00.000 Travel Time 28:30:0
    3 nick 2014-03-02 00:00:00.000 2014-03-08 00:00:00.000 Mon 2014-03-03 00:00:00.000 Onsite/WalkTesting 40:0:0
    4 john 2014-03-23 00:00:00.000 2014-03-29 00:00:00.000 Mon 2014-03-24 00:00:00.000 Onsite/WalkTesting 42:0:0
    5 test 2014-03-09 00:00:00.000 2014-03-15 00:00:00.000 Mon 2014-03-10 00:00:00.000 Travel Time , 34:15:0
    6 ema 2014-04-13 00:00:00.000 2014-04-19 00:00:00.000 Mon 2014-04-14 00:00:00.000 Equipment Testing 39:0:0
    output for ComExpenseTable 
    CExpID airfare hotel weeklycomexpensetable 1 45.00 34.00 213.00
    3 5.00 3.00 16.00
    6 5.00 3.00 16.00
    output  for  Perexpensetable
    PExpID PerExpenseTable1 Sun 2014-02-02 00:00:00.000 199.00
    2 Sun 2014-02-23 00:00:00.000 199.00
    below  query for sum of indivial expense in company table
    select sum(CHotel) as Hotel ,sum(CTransport) as Airfare,sum(CMeals) as Meals,sum(CFuel) as Gas,sum(CTolls),Sum(CParking) as Parking,Sum(CMisc) as Misc ,sum(CMileage) as Mileage from ComExpensesTable where CExpID=1
    Now  I want  to add  sum of hotel,transport ..  to  the below query  .I don't  know how  to do this.Any suggestions please?
    select distinct(e.EmpID) ,e.EmpName, e.StartDate,e.EndDate,e.Total,c.WeeklyComtotalExpenses,p.WeeklyPerTotalExpenses
    from EmpTimeSheet e left JOIN ComExpensesTable c on c.CExpID=e.EmpID left join PerExpensesTable p ON p.PExpID=e.EmpID

    select
    distinct(e.EmpID) ,
    e.EmpName,
    e.StartDate,
    e.EndDate,
    e.Total,
    ee.Hotel,
    ee.Airfare,
    c.WeeklyComtotalExpenses,
    p.WeeklyPerTotalExpenses
    fromEmpTimeSheet e
    left JOIN (select CExpID, sum(CHotel) as Hotel ,sum(CTransport) as Airfare,
    sum(CMeals) as Meals,sum(CFuel) as Gas,sum(CTolls),
    Sum(CParking) as Parking,Sum(CMisc) as Misc ,
    sum(CMileage) as Mileage from ComExpensesTable group by CExpID) cleft join // don't need the "left join" hereon c.CExpID=e.EmpID //error
    left join PerExpensesTable p ON p.PExpID=e.EmpID

  • Custom aggregate function inside a package.

    Hi there,
    I'm trying to write a custom aggregate function and group that function inside a package together with some other functions that I have. As an example (to simulate the problem I have) suppose my custom aggregation to do a summation of numbers looks like:
    CREATE OR REPLACE TYPE SUM_AGGREGATOR_TYPE AS OBJECT (
    summation NUMBER,
    STATIC FUNCTION ODCIAggregateInitialize(agg_context IN OUT
    SUM_AGGREGATOR_TYPE) RETURN NUMBER,
    MEMBER FUNCTION ODCIAggregateIterate(self IN OUT SUM_AGGREGATOR_TYPE,
    next_number IN NUMBER) RETURN NUMBER,
    MEMBER FUNCTION ODCIAggregateMerge(self IN OUT SUM_AGGREGATOR_TYPE,
    para_context IN SUM_AGGREGATOR_TYPE) RETURN NUMBER,
    MEMBER FUNCTION ODCIAggregateTerminate(self IN SUM_AGGREGATOR_TYPE,
    return_value OUT NUMBER, flags IN NUMBER) RETURN NUMBER
    CREATE OR REPLACE TYPE BODY SUM_AGGREGATOR_TYPE IS
    STATIC FUNCTION ODCIAggregateInitialize(agg_context IN OUT
    SUM_AGGREGATOR_TYPE)
    RETURN NUMBER IS
    BEGIN
    agg_context := SUM_AGGREGATOR_TYPE(NULL);
    RETURN ODCIConst.Success;
    END;
    MEMBER FUNCTION ODCIAggregateIterate(self IN OUT SUM_AGGREGATOR_TYPE,
    next_number IN NUMBER)
    RETURN NUMBER IS
    BEGIN
    IF self.summation IS NULL THEN
    self.summation := next_number;
    ELSIF summation IS NOT NULL THEN
    self.summation := self.summation + next_number;
    END IF;
    RETURN ODCIConst.Success;
    END;
    MEMBER FUNCTION ODCIAggregateMerge(self IN OUT SUM_AGGREGATOR_TYPE,
    para_context IN SUM_AGGREGATOR_TYPE)
    RETURN NUMBER IS
    BEGIN
    self.summation := self.summation + para_context.summation;
    RETURN ODCIConst.Success;
    END;
    MEMBER FUNCTION ODCIAggregateTerminate(self IN SUM_AGGREGATOR_TYPE,
    return_value OUT NUMBER, flags IN NUMBER)
    RETURN NUMBER IS
    BEGIN
    return_value := self.summation;
    return ODCIConst.Success;
    END;
    END;
    If I write the following function definition:
    CREATE OR REPLACE FUNCTION MY_SUM(input NUMBER)
    RETURN NUMBER PARALLEL_ENABLE AGGREGATE USING SUM_AGGREGATOR_TYPE;
    and corresponding type declaration to test:
    CREATE OR REPLACE TYPE VECTOR
    IS
    TABLE OF NUMBER;
    this statement:
    select my_sum(column_value) from table(vector(1, 2, 1, 45, 22, -1));
    gives the correct result of 70. However, creating a package with the function definition:
    CREATE OR REPLACE PACKAGE MY_FUNCTIONS AS
    FUNCTION MY_SUM(input NUMBER)
    RETURN NUMBER PARALLEL_ENABLE AGGREGATE USING SUM_AGGREGATOR_TYPE;
    END;
    and calling it via:
    select MY_FUNCTIONS.my_sum(column_value) from table(vector(1, 2, 1, 45, 22, -1));
    explodes with:
    ORA-00600: internal error code, arguments: [17090], [], [], [], [], [], [], [], [], [], [], []
    Is it possible to have custom aggregate functions nested inside package declarations?
    I'm using Oracle 11g, Release 2 (11.2.0.1.0).

    HiddenName wrote:
    Is it possible to have custom aggregate functions nested inside package declarations?Yes, it is possible, you have succesfuly created your function. Your problem is that the database throws ORA-600 on execute. And with ORA-600 you can do 2 things: 1) google ORA-600 17090 or 2) contact your Oracle Support.
    You could also try to declare the function without PARALLEL_ENABLE - just to try to see if it changes anything. You can also try to call your function against a regular table with rows and columns - not against an collection type with table() operator.
    Anyway - these 2 tests should be usefull for Oracle Support.
    I never tried to put a custom aggregate function into a package. First - the cases when you need a custom aggregate function to be written for your system are very rare. Second - even if I needed 1 then I never needed 2 or more custom aggregate functions on my system. And as I do not like to make my life more complex than necessary, I have created it as a stand-alone function. And it is works (slowly).I tried using a standard table as you suggested:
    CREATE TABLE TEST_DATA
    test_value NUMBER
    INSERT INTO TEST_DATA
    (SELECT column_value test_value from TABLE(vector(1, 2, 1, 45, 22, -1)));
    COMMIT;
    select my_sum(test_value) from test_data;
    select my_functions.my_sum(test_value) from test_data;
    I also tried removing the PARALLEL_ENABLE clause to create the package as follows:
    CREATE OR REPLACE PACKAGE MY_FUNCTIONS AS
    FUNCTION MY_SUM(input NUMBER)
    RETURN NUMBER AGGREGATE USING SUM_AGGREGATOR_TYPE;
    END;
    And unfortunately it still breaks with the following error: SQL Error: ORA-00600: internal error code, arguments: [17090]. This looks like an Oracle bug to me as the PL/SQL parsing engine should have disallowed me to even create this if it is not supported in Oracle. Instead, it allows me to create the package, and breaks when I call the function with this weird error (additionally cutting my connection from the database) instead of disallowing me to do this altogether and printing a nice error message telling me that Oracle doesn't support this. How would I go about logging a ticket for this?
    Edited by: wcmatthysen on Dec 1, 2010 12:51 PM

  • 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

Maybe you are looking for