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

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;

  • 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

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

  • Defining STDEV as an aggregate function

    Is there a way to force BO XI R2 to recognize SQL function STDEV as an aggregate function?
    I found a reference for version 6.5 in the following link but I can't implement the suggested solution:
    http://www.forumtopics.com/busobj/viewtopic.php?p=701261&sid=8e2cfd855db2069cb84d9e021a5ba4a5
    Thanks,
    Paulo Gottlib

    Rank syntax is
         rank( expression1, ... expression_n ) WITHIN GROUP ( ORDER BY expression1, ... expression_n )for example we are going to find employee salary and comm
    select rank(1000, 500) WITHIN GROUP (ORDER BY sal, comm) from emp;The SQL statement above would return the rank of an employee with a salary of $1,000 and a commision of $500 from within the emp table.
    Now we are going to find from your table like this
    first of all run this query
    select * from employee order by salary, JOB_IDyour result will be like this
    RowNum ID JOB_ID SALARY
    1     100 667 800
    2     200 670 1250
    3     300 670 1250
    4     400 670 1600
    5     500 671 2200
    6     600 671 2750
    7     700 671 2850----------------------------------------------------------------------------------------
    select rank(2650,671) within group (order by salary, JOB_ID) from employeeit will be return value 6 because salary 2650 near to row 6 (Salary = 2750)
    similarly
    select rank(1900,670) within group (order by salary, JOB_ID) from employeeit will be return value 5 because salary 1900 near to row 6 (Salary = 2200)
    select rank(800, 671) within group (order by salary, JOB_ID) from employee
    this query return value 2 (reason is that)
    salary = 800 exist on row number 1
    and Job_ID = 671 exist on row_num 5 to 7due to salary and job_id both don't match so query will return those value where salary has min difference
    Now check
    select rank(1250, 671) within group (order by salary, JOB_ID) from employeesimilarly it will be return value 4
    .... Thanks & Regards ....
    --------Syed Adeel Ali-------
    ----------------------------------------------------------------------------------------

  • 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

  • Problem with aggregate function

    Hello,
    the prerequisite is to have a table with the following columns (#id, a_date).
    Now the task is to select the maximum date from a range of rows of this table
    select max(t.a_date)
    from the_table t
    where <condition to get only some rows of the_table>
    and to get the id of the record which holds the maximum date. That's where the problem is located. It should look like the following code (yes, I know this cannot work because grouping by the id makes the aggregate senseless) just to make clear what I want to do.
    select max(t.a_date), t.id
    from the_table t
    where <condition to get only some rows of the_table>
    group by t.id
    Does anybody have any idea how to solve the problem?
    With regards,
    Cosima
    Message was edited by:
    Cosima Laube

    Hi all,
    as the condition in the where-clause is very complex, I decided to use the solution with the FIRST function. After googling and reading a bit, I have just two more questions for my deeper understanding:
    1) am I right that both snippets below do exactly the same?
    SELECT MAX (t.a_date)
         , MAX (t.ID)KEEP (DENSE_RANK FIRST ORDER BY t.a_date DESC)
      FROM the_table t
    WHERE <condition to get only some rows of the_table>
    SELECT MAX (t.a_date)
         , MAX (t.ID)KEEP (DENSE_RANK LAST ORDER BY t.a_date ASC)
      FROM the_table t
    WHERE <condition to get only some rows of the_table>2) can I use als the min function for t.ID as there the aggregate function does not have any effect (but is necessary in order to use KEEP and FIRST or KEEP and LAST)?
    With regards,
    Cosima
    Message was edited by:
    Cosima Laube

  • Select into aggregate function

    Hi,
    I have the following PL/SQL block that I am testing. The block reads a list of values from a local file and inserts the values into a select statement that uses an aggregate function. Here is my code:
    DECLARE
    f utl_file.file_type;
    n COLa%TYPE; --holds values from the file
    v COLb%TYPE; --holds value returned by select statement
    BEGIN
    f := utl_file.fopen(dir,file.txt,'R');
    loop -- loop through file
         utl_file.get_line(f,n);
         if length(n) <> 0 then
              SELECT max(A0.COLa) into v
              FROM (SELECT AOB.COLa, A0.COLb
              FROM TAB1 A0,TAB2 A0B
              WHERE (A0.PK=A0B.PK) and A0B.COLa = n) A0;          
              IF SQL%rowcount = 0 THEN
                   dbms_output.put_line('no rows);
              else
                   dbms_output.put_line(v);
              end if;                    
         end if;     
    end loop;
         utl_file.fclose(f);     
    end;
    Here is the error I get:
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at "SYS.UTL_FILE", line 98
    ORA-06512: at "SYS.UTL_FILE", line 656
    ORA-06512: at line 12
    I checked the database for the first couple of values in the list and got rows. I also ran a simple PL/sql code to print values in the file successfully. So I dont know why it is returning no data found. From what I understand select into statement using aggregate functions will never raise this exception, so why I am getting this error?
    Thanks.

    Hi,
    Actually, the SELECT ... INTO isn't the problem here.
    Look at the error message:
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at "SYS.UTL_FILE", line 98
    ORA-06512: at "SYS.UTL_FILE", line 656
    ORA-06512: at line 12The error is ocurring inside utl_file, which is being called at line 12 of your code. (That must be
    utl_file.get_line(f,n);)
    Utl_file.get_line raises NO_DATA_FOUND when it reaches the end of the file. (If it didn't you'd have an infinite loop, since your code doesn't have any exit strategy.)
    You can put the call to get_line in its won BEGIN-EXCEPTION-END block, and trap the NO_DATA_FOUND error.
    For example:
    end_of_file := 0;
    WHILE  end_of_file = 0;
    loop -- loop through file
        BEGIN
            utl_file.get_line(f,n);
            if length(n) != 0 then          -- Use !=, because you can't post &lt;&gt; on this site
                SELECT  max(A0B.COLa)     -- No sub-query needed
                into    v
                FROM    TAB1 A0
                ,         TAB2 A0B
                WHERE   (A0.PK   = A0B.PK)
                and         A0B.COLa = n;
                IF SQL%rowcount = 0 THEN     -- Not needed: SELECT MAX ... without GROUP BY always returns 1 row
                    dbms_output.put_line('no rows);
                else
                    dbms_output.put_line(v);
                end if;
            end if;
        EXCEPTION
            WHEN  NO_DATA_FOUND
            THEN
                end_of_file = 1;
        END;
    end loop;Edited by: Frank Kulash on Jul 17, 2009 2:51 PM

  • The COLLECT aggregate function

    Hi,
    Need some help understanding the COLLECT aggregate function.
    My requirement is to concatenate all Varchar2 strings in a column into a single Varchar2 string...
    The follwing thread seems somewhat relevant to the requirement....
    collect(distinct X))
    Thanks.

    The COLLECT docs specifically refer to working with nested tables. Are you working with one? If so post the DDL. There is a demo in Morgan's Library here: http://www.psoug.org/reference/collect_func.html#ccol
    Personally this would be the last thing I'd thing of if the goal is as you state it. Well maybe not the last but far from the first.
    I'd suggest looking at WM_CONCAT and then using TRANSLATE to replace the commas with '||'.
    There is a demo of WM_CONCAT in Morgan's Library at www.psoug.org also.
    But do check Tom Kyte's site: http://asktom.oracle.com
    This is the type of thing Tom posts and his code is far better than mine.

  • How to Passing clob to PL/SQL pipeline function

    I have a PL/SQL stored function which takes clob as input parameter and sends the results in a pipe line.
    create or replace function GetIds(p_list clob, p_del varchar2 := ',') return ideset_t pipelined is
    I am using ojdbc14.jar (Oracle 10g driver) with oracle 9i (9.2.0.1.0).
    I want to use the following SQL Query select * from table(GetIds(clob))
    Now the question is how can I pass the clob from JDBC?
    Here is my client code
    PreparedStatement stmt = con.prepareStatement("SELECT COLUMN_VALUE FROM TABLE(GETIDS(?, ','))");
    stmt.setCharacterStream(1, new StringReader(str), str.length());
    stmt.executeQuery();
    I get the following error when I try to run the program. The same thing works fine if the chracter lenght is less than some chaaracters.
    java.sql.SQLException: ORA-01460: unimplemented or unreasonable conversion requested
         at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:305)
         at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:272)
         at oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:623)
         at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:181)
         at oracle.jdbc.driver.T4CPreparedStatement.execute_for_describe(T4CPreparedStatement.java:420)
         at oracle.jdbc.driver.OracleStatement.execute_maybe_describe(OracleStatement.java:896)
         at oracle.jdbc.driver.T4CPreparedStatement.execute_maybe_describe(T4CPreparedStatement.java:452)
         at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:986)
         at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:2888)
         at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:2960)
         at Test.main(Test.java:42)
    Exception in thread "main"
    The setChracterStream works for any insert/update clob. Example when I tried the query (INSERT INTO CLOB_TEST VALUES(?)) setCharacterStream just works fine.
    Please any one can help me how to solve this.
    Thanks in advance.

    Hóla LuÃs,
    when you pick the PL/SQL function body returning a boolean, it implicitly means that TRUE means OK, while FALSE means error, always.
    In order to associate such error to a given form field, you have to go back to the page definiton / validations and specify the name of the item in the corresponding field.
    When you first create the validation rule, this value is not present even if you ask for the error message inline with the field.
    The error message text can be specified in the validation definition, if I am not wrong.
    When you need to return special error messages, including dynamic content for instance, you can use the Function Returning Error Message type, which reports an error when the string returned by the function is not null. This comes in handy when you want to display an item's code, for example, rather than generic text.
    Even in this case, you must go back to the validation and specify the name of the field if you want to see it inline.
    Hope it helps,
    Flavio

Maybe you are looking for

  • Parameters & Not all variables bound

    select like this: select * from t_department where (:param is null and parent_id is null) or parent_id = :param OracleParameter Param = new OracleParameter("param",OracleDbType.NVarchar2,null,ParameterDirection.Input); dbCommand.Parameters.Add(Param)

  • PO error in SUS-MM Scenario

    We are implementing SUS-MM scenario. A purchase order is created in R/3 and sent over to SUS. When it comes to SUS it errors out with the following error. The Business partner it is looking for is company code. Which is there in the system. any ideas

  • How to change the "from email id" of all the notifications in the instance

    Hi, I have a requirement to change the from email address of all the outbound notifications in an instance. Presently our notifications are having from address as R12 Workflow Mailer ["[email protected]"] We want to change this to ABC. So that all th

  • Saving highlight text as pdf

    Is there any way to save just highlighted items on safari as a pdf? Just because images are irrelevant to my savings.

  • Acrobat X Pro 10.1.6 not opening since upgrading to IE10

    Since upgrading to IE10, I can't open pdfs online. No problems opening off-line. Had the same problem with Java and had to upgrade to 64-bit version. Any way to solve this since AAX is 32-bit? Thanks!