Aggregate functions, %notfound and group by

Hi,
Below are 2 versions of a script that query the employees table and get the max salary by specific departments. Department ids are held in a varray.
With 'group by':
declare
    type c is ref cursor;
    c1 c;
    sal employees.salary%type;
    type rid is varray(3) of number;
    r_id rid:=rid();
begin
r_id.extend(3);
r_id(1):=50;
r_id(2):=80;
r_id(3):=200;
for y in 1..3
loop
open c1 for select max(salary) from employees
where department_id =r_id(y)
group by department_id;
                    fetch c1 into sal;
                    if c1%notfound then                         
                    dbms_output.put_line('not found');
                    else
                    dbms_output.put_line(sal);
                    end if;
    close c1;
end loop;
end;No 'group by':
declare
    type c is ref cursor;
    c1 c;
    sal employees.salary%type;
    type rid is varray(3) of number;
    r_id rid:=rid();
begin
r_id.extend(3);
r_id(1):=50;
r_id(2):=80;
r_id(3):=200;
for y in 1..3
loop
open c1 for select max(salary) from employees
where department_id =r_id(y);
                    fetch c1 into sal;
                    if c1%notfound then                         
                    dbms_output.put_line('not found');
                    else
                    dbms_output.put_line(sal);
                    end if;
    close c1;
end loop;
end;The version with no group by clause always returns false for cursor attribute %notfound. Whereas in the version with the clause %notfound is true when an non-existent department id is entered. Why is this?
Product info: Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
PL/SQL Release 10.2.0.1.0
Thanks.

<strike>Because the group by works on the rows that are returned from the where clause, and then the columns are applied. If you pass a condition into the where clause that causes no rows to be returned, then there's nothing to group by,
Whereas when you select an aggregate query without a group by, you always get a row returned.
eg: select count(*) from (
select max(dummy)
from   dual
where  dummy = 'Y')
  COUNT(*)
         1
select count(*) from (
select max(dummy)
from   dual
where  dummy = 'Y'
group by dummy)
  COUNT(*)
         0</strike>
Edited by: Boneist on 19-Aug-2009 15:21
Hmm... the documention seems to indicate that you should always get a row back, even if it's null.
I have no idea why adding the group by causes that statement to not be true, then, unless I'm misunderstanding the documentation!!

Similar Messages

  • Analytic function and aggregate function

    What are analytic function and aggregate function. What is difference between them?

    hi,
    Analytic Functions :----------
    Analytic functions compute an aggregate value based on a group of rows. They differ from aggregate functions in that they return multiple rows for each group. The group of rows is called a window and is defined by the analytic_clause. For each row, a sliding window of rows is defined. The window determines the range of rows used to perform the calculations for the current row. Window sizes can be based on either a physical number of rows or a logical interval such as time.
    Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.
    Analytic functions are commonly used to compute cumulative, moving, centered, and reporting aggregates.
    Aggregate Functions :----------
    Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause, the elements of the select list can be aggregate functions, GROUP BY expressions, constants, or expressions involving one of these. Oracle applies the aggregate functions to each group of rows and returns a single result row for each group.
    If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view. You use aggregate functions in the HAVING clause to eliminate groups from the output based on the results of the aggregate functions, rather than on the values of the individual rows of the queried table or view.
    let me know if you are feeling any problem in understanding.
    thanks.
    Edited by: varun4dba on Jan 27, 2011 3:32 PM

  • Self Join and Aggregate Functions

    Hi all,
    I am trying a query in TOAD where I need to use an aggregate function MAX and a self join using a subquery. Its working fine when there is no aggregate function but when I tried to use the MAX function then its running for infi time. Is it because of the invalid joins? or because of the usage of the self join and aggregate func?
    The query contains some other tables too....
    Any one please help....
    Thanks in advance,
    G

    Toad will bring back a limited set of rows and present them to you giving the impression that the work is done. Adding an aggregate function requires the entire resultset to be traversed.
    Yes, post the 2 queries to verify what I am saying.

  • Function count() meets group by

    Hi guys,
    I got an application error, and the root cause is like below, not sure if anyone have same experience:
    We will validate the return row count, and it's tricky that the old code was LIKE:
    SELECT COUNT(1) FROM table_name WHERE 1 != 1;
    0
    the output is only one row.
    BUT, when we add a "GROUP BY", why it doesn't return any record:
    SELECT COUNT(1) FROM table_name WHERE 1 != 1 GROUP BY col_name;
    output is nothing.
    Why the result is different with "GROUP BY"?
    Edited by: Wang, Chen on Jul 4, 2012 7:31 PM
    Edited by: Wang, Chen on Jul 4, 2012 7:44 PM

    Hi,
    The COUNT() function (and other aggregate functions) works exactly as described in Oracle documentation. It is not commonly known behaviour however it is well documented in standard Oracle documentation. Yes, there is a very slight difference how aggregate functions are evaluated with and without GROUP BY clause.
    Oracle® Database SQL Language Reference 11g Release 2 (11.2)
    Aggregate Functions
    Aggregate functions return a single result row based on groups of rows, rather than on single rows. Aggregate functions can appear in select lists and in ORDER BY and HAVING clauses. They are commonly used with the GROUP BY clause in a SELECT statement, where Oracle Database divides the rows of a queried table or view into groups. In a query containing a GROUP BY clause, the elements of the select list can be aggregate functions, GROUP BY expressions, constants, or expressions involving one of these. Oracle applies the aggregate functions to each group of rows and returns a single result row for each group.
    If you omit the GROUP BY clause, then Oracle applies aggregate functions in the select list to all the rows in the queried table or view. You use aggregate functions in the HAVING clause to eliminate groups from the output based on the results of the aggregate functions, rather than on the values of the individual rows of the queried table or view.So if you have the GROUP BY clause then Oracle will first apply the WHERE clause to filter out records, then it will form groups, i.e. look for each distinct value of col_name and finally it will apply the aggregate function to each group of rows and return a single result row for each group. Because after evaluation of WHERE 1 != 1 there is nothing left (zero records) then there will zero groups formed and there will be one row returned for each of zero groups -> no rows returned.
    It works differently when you omit the GROUP BY clause. Oracle applies aggregate functions to all the rows in the queried table or view. If there is no GROUP BY then it is known upfront that Oracle will have exactly one group of rows. So there is already one group of rows before WHERE clause is evaluated. And you will always get this one row returned for aggregate functions.
    This is not a bug. This is by design. It works as it should and as it is documented. It is a nuance of SQL language that is not commonly known or frequently forgotten, but it is not a problem of Oracle or SQL language.

  • Aggregate Function for Text Column???

    Hi,
    Is there a way to group a column's values appearing in multiple rows ( all having some similarity) to be grouped into one single column in one Single Row??
    To be more precise,
    do we have an Aggregate function which would group values ( may be using commas for separation) for a single column appearing in multiple rows when "grouped By" on some condition.

    See here:
    http://www.oracle-base.com/articles/10g/StringAggregationTechniques.php
    Rgds.

  • Aggregate functions cannot be used in group expressions

    Hi have report showing sales by Vendor. I need to list all the vendors with Monthly Total>5000 and combine the rest as "OTHER VENDORS"
    Vendor is a Group in my report, so I tried to put an expression as a Group on:
    =IIF(Sum(Fields!Mth_1_Sales.Value)>5000,Fields!Vendor_No.Value,"OTHER VENDORS")
    I've got an error: "aggregate functions cannot be used in group expressions"
    How do I get Vendors with Sales < 5000 into  "OTHER VENDORS" ?

    Hi,
    You need to group by Month on group expression,
    And you can use the same expression in the report column as 
    =IIF(Sum(Fields!Mth_1_Sales.Value)>5000,Fields!Vendor_No.Value,"OTHER VENDORS")
    Many Thanks
    ..................................................................................................................................................................Please
    mark the post as Please mark the post as answered if this post helps to solve the post.

  • 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

  • Group By Select Statement aggregate function error.

    I am using Dreamweaver MX4 and have an ASP web page. I can easily do this in Access 2007 a simple "group by" sum totals statement.
    Why can I not get this to work on a web page? Are the "#" signs messing this up in the Code2 Select Statement?
    How can I get Code2 to work correctly? Code1 works fine. A user enters the customer and a date range on a form and submits request. I get error message in Dreamweaver. You tried to execute a query where the specified expression field3 is not part of an aggregate function
    Code1. This works fine SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #1/2/09# AND Field6 <= #1/30/09#  GROUP BY Field3, Field10
    Code2. I get error message SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #Date1# AND Field6 <= #Date2#  GROUP BY Field3, Field10

    I am using Dreamweaver MX4 and have an ASP web page. I can easily do this in Access 2007 a simple "group by" sum totals statement.
    Why can I not get this to work on a web page? Are the "#" signs messing this up in the Code2 Select Statement?
    How can I get Code2 to work correctly? Code1 works fine. A user enters the customer and a date range on a form and submits request. I get error message in Dreamweaver. You tried to execute a query where the specified expression field3 is not part of an aggregate function
    Code1. This works fine SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #1/2/09# AND Field6 <= #1/30/09#  GROUP BY Field3, Field10
    Code2. I get error message SELECT Field3, Field10, SUM(Field16) as SumofField16 FROM CustomerHistory_CP WHERE Field3 LIKE '%Search_Criteria%' AND Field6 >= #Date1# AND Field6 <= #Date2#  GROUP BY Field3, Field10

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

  • TableModel with SORT and GROUP BY functions solution.

    Hello all,
    I'd like to represent an EnvelopeTableModel. This class is developed to incapsulate another TableModel and allow user to reorder and group data without changing original values and orders.
    It allows to perform multi column sortings and grouping and
    supports following group functions: EMPTY, COUNT, MIN, MAX, SUM, AVG.
    Here you can download the library, demo version and documentation.
    http://zaval.org/products/swing/
    It would be great to know all your opinions.
    With best regards
    Stanislav Lapitsky

    About 1) and 3).
    These suggestions are almost the same. These features will change GUI component but i want to improve TableModel instead of JTable.
    Using the model user can use JTable for data representation.
    Of course I can improve JTable component and add multiline row/column headers with ability to reorder/group data from component and a lot of another widgets but it isn't my goal.
    About 2) What do you mean "crosstab"?
    Thanks for your 2-cents :-).
    With best regards
    Stas

  • 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

  • Table name in which function module and function group store

    Hai,
    Any one help me, What is the table name, the function modules and fouction groups are stored.
    Thanks,
    Elamaran

    ...and table enlfdir has additional info.... function module RS_GET_ALL_INCLUDES is useful for getting a list of includes used by an fm.
    Message was edited by: Neil Woodruff

  • Need complex query  with joins and AGGREGATE  functions.

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

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

  • Java JDBC-ODBC GROUP BY (aggregate function) error

    I get the error
    "java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] You tried to execute a query that does not include the specified expression 'CUSTOMER_ID' as part of an aggregate function."
    when I try to execute the following query:
    PreparedStatement stmt = connection.prepareStatement(
    "SELECT Customers.customer_id, Customers.customer_name, SUM(Transactions.surcharge) AS surcharge, SUM(Transactions.interchange) AS interchange, SUM(Transactions.approved) AS transactions " +
    "FROM (Customers INNER JOIN Terminals ON Customers.customer_id = Terminals.customer_id) " +
    "INNER JOIN Transactions ON Terminals.terminal_id = Transactions.terminal_id " +
    "WHERE Transactions.transaction_date=#12/8/2003# " +
    "GROUP BY Customers.customer_id, Customers.customer_name",
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY
    Funny thing is this query works fine when I execute it in Microsoft Access directly. I can't figure out what's causing the problem. Any help?

    Have you tried:
    PreparedStatement stmt = connection.prepareStatement(
    "SELECT Customers.customer_id, Customers.customer_name, SUM(Transactions.surcharge) AS surcharge, SUM(Transactions.interchange) AS interchange, SUM(Transactions.approved) AS transactions " +
    "FROM (Customers INNER JOIN Terminals ON Customers.customer_id = Terminals.customer_id) " +
    "INNER JOIN Transactions ON Terminals.terminal_id = Transactions.terminal_id " +
    "WHERE Transactions.transaction_date=#12/8/2003# " +
    "GROUP BY customer_id, customer_name",
    ResultSet.TYPE_SCROLL_INSENSITIVE,
    ResultSet.CONCUR_READ_ONLY
    (Who knows ?... Sometimes SQL engines are very strangely built!)

  • FetchXML and Aggregate Functions (multiple datasets if necessary)

    In fetch xml,
    How do I do conduct aggregate functions (most recent, sum, average) on retrieved columns, based on matches with another column.
    let's say column a has a value of "Timothy."
    How do I then find the total number of column b that also have a value of 'Timothy?'
    But then the next value of column a is 'John.'
    I would then want to display the total number of column b that have a value of 'John?'
    If this is totally impossible, could introducing another dataset help?
    Sql is not available here and fetchxml can only do so much.  So this is going to have to be done with variables in the actual report.

    Looks like you're using Dynamics CRM. If that being the case, you may be better off posting in MS Dynamics forums. This forum is specifically for Reporting Services and Power view
    Please Mark This As Answer if it solved your issue
    Please Vote This As Helpful if it helps to solve your issue
    Visakh
    My Wiki User Page
    My MSDN Page
    My Personal Blog
    My Facebook Page

Maybe you are looking for

  • Post a goods issue on a close period

    Dear Gurus, We need to correct some material documents due to fiscal inconsistences, but these documents were posted on a closed period (May). Currently, the periods open are June and July. Is there a way we can do that? Regards. Fabio Scaravelli

  • Dual monitor issue with 10.8 and Windows 7 (bootcamp)

    I've a read a lot of threads here about people having nightmare-ish problems after upgrading.  Thankfully, this isn't one of them, just a frustration that I'd like advice on. My system:  2010 13" MBP, 2.4GHz Intel Core 2 Duo, 8GB RAM, 320GB HD.  Work

  • Acrobat 9.3 And Office 2010 PDFMaker Issue

    Hello: From the Adobe knowledge base I found that the Acrobat Menu Ribbon Tab for PDFMaker which is normally visible from within Word, Excel or PowerPoint does not appear in Office 2010.  This was to be fixed in Acrobat X, but since I haven't acquire

  • How to execute this SQL Query in ABAP Program.

    Hi, I have a string which is the SQL Query. How to execute this sql Query (SQL_STR) in ABAP Program. Code:- DATA: SQL_STR type string. SQL_STR = 'select * from spfli.'. Thanks in Advance, Vinay

  • Updating or changing the outbound delivery

    Hi we have created a outbound delivery in the system, I want to update some of the detials like route, no of packages using a program. is there any FM or BAPI for that. I have tried using the  BAPI_OUTB_DELIVERY_CHANGE to update the route in the deli