Subquery in the HAVING Clause

Hello all,
i'm getting error when i try to write sub query in having clause. check out my query
select  ROUND( Count( distinct  Sales2011_DIVDPTA.DIVDPTA_Item_Dept ),0)  AS  "F1" , ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)  AS  "F2"  
from Sales2011.Sales2011_JT    
  INNER JOIN Sales2011.Sales2011_DG1 On Sales2011.Sales2011_DG1.DG1_ID =Sales2011.Sales2011_JT.DG1_ID   
LEFT JOIN Sales2011.Sales2011_DIVDPTA On nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DIVISION,' ')=nvl(Sales2011.Sales2011_DG1.Item_Division,' ')
  AND  nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DEPT,' ')=nvl(Sales2011.Sales2011_DG1.Item_Dept,' ')       
having ( ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)     in ( 0)
But it is not executed if I use the sub query in having clause
select  ROUND( Count( distinct  Sales2011_DIVDPTA.DIVDPTA_Item_Dept ),0)  AS  "F1" ,  ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)  AS  "F2"   
from Sales2011.Sales2011_JT       
INNER JOIN Sales2011.Sales2011_DG1 On Sales2011.Sales2011_DG1.DG1_ID =Sales2011.Sales2011_JT.DG1_ID   
LEFT JOIN Sales2011.Sales2011_DIVDPTA On nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DIVISION,' ')=nvl(Sales2011.Sales2011_DG1.Item_Division,' ')
AND  nvl(Sales2011.Sales2011_DIVDPTA.DIVDPTA_ITEM_DEPT,' ')=nvl(Sales2011.Sales2011_DG1.Item_Dept,' ')        
having ( ROUND( Count( Sales2011.Sales2011_DG1.Item_Season ),0)
in ( select   ROUND( Count(
Sales2011.Sales2011_DG1.Item_Season ),0)  from    Sales2011.Sales2011_DG1 )
Error at Command Line:1 Column:0
Error report:
SQL Error: ORA-00979: not a GROUP BY expression
00979. 00000 -  "not a GROUP BY expression"
*Cause:   
*Action:any help ???

Sorry unintentionally i have posted my question here.
will you please elaborate this? Becoz i'm not using group by clause in both query. First query run successfully but as i put sub query in having clause it raised an error. will you tell where i'm committing mistake?
Aggregates in the HAVING clause do not need to appear in the SELECT list. If the HAVING clause contains a subquery, the subquery can refer to the outer query block if and only if it refers to a grouping column.Edited by: Oracle Studnet on Aug 14, 2011 11:28 PM

Similar Messages

  • Subquery in the Where clause

    Can I put a subquery in the where clause, on the left side on the operator?
    This is a multi-row query.
    Like this,
       select a.col1, a.col2, b.col1, b.col2,
                 my_function(a.date1, b.date2) AS GROSSDAYS
       from table1 a
       where ( select ( a.date1 - b.date2 ) as range
                   from     table1 a
                   join      table2 b
                   on       a.col3 = b.col3
                   where rownum =1
                   in ( 1,2,3)
    and  a.col1 = b.col2I need to use a subquery because the column I need does not exist in the table, and I cannot make any changed to the table structure.
    Is what I'm doing possible?
    The subquery is the same as the function I have in the Select clause.

    I tried a subquery in the where clause, but now I'm getting a missing expression error!
       SELECT
            r.complete_flag, r.order_num, r.referral_num, TRUNC(r.referral_datetime) AS referral_datetime,
            r.clinic_specialty, a.appointment_datetime, TRUNC(a.appointment_date_made) AS appt_datemade, a.appointment_status_id,
             scref.scr_rules.calcatcdays(r.referral_datetime,a.appointment_date_made) AS ATCDays  -- returns difference between two dates
    FROM
            referral r,
                                 ( SELECT referral_num,appointment_datetime, appointment_date_made, appointment_status_id
                                      FROM   ( SELECT referral_num, appointment_datetime, appointment_date_made, appointment_status_id,
                                                ROW_NUMBER() OVER (PARTITION BY referral_num
                                                ORDER BY appointment_datetime) rn
                                            FROM   appointment
                                     WHERE rn = 1
                             a
    WHERE r.order_num IS NOT NULL
    AND   ( SELECT adays                      -- THIS IS WHERE I'M GETTING A MISSING EXPRESSION ERROR!!!
           FROM ( SELECT scref.scr_rules.calcatcdays(r.referral_datetime,a.appointment_date_made) AS adays
                    FROM referral r
                     JOIN appointment a
                     ON   a.referral_num = r.referral_num
                     WHERE ROWNUM = 1
           WHERE  adays
          ) = 3
    AND   r.referral_num = a.referral_num(+)
    AND   TRUNC(r.referral_datetime) >= TO_DATE('01-JUL-05','DD-MON-YY')
    AND   TRUNC(r.referral_datetime) <= TO_DATE('31-JUL-05','DD-MON-YY')

  • Subquery in the From Clause

    I have a query the contains a subquery in the from clause. The problem is how to join one of the tables in the subquery to one of the main tables. If I hard a value, the query runs, but using a table.column produced an "invalid column name" error.
    Examples of both are below.
    This one works
    SELECT a.pay_rate, a.bill_rate, a.frequency, c.value
    FROM SYSADM.ps_pb_wkord_sq_rte a, SYSADM.ps_md_erncd_action b,
    SELECT DISTINCT z.value
    FROM SYSADM.ps_md_erncd_action z
    WHERE z.md_action = 'CALC_BURD' AND
    z.system_id = 'PB' AND
    z.erncd = 'REG' AND **This is the line in question**
    z.effdt = (
    SELECT MAX(z_ed.effdt)
    FROM SYSADM.ps_md_erncd_action z_ed
    WHERE z.setid = z_ed.setid AND
    z.erncd = z_ed.erncd AND
    z.effdt = z_ed.effdt AND
    z.system_id = z_ed.system_id AND
    z.md_action = z_ed.md_action AND
    z_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY'))) c
    WHERE a.erncd = b.erncd AND
    b.effdt = (
    SELECT MAX(b_ed.effdt)
    FROM SYSADM.ps_md_erncd_action b_ed
    WHERE b.setid = b_ed.setid AND
    b.erncd = b_ed.erncd AND
    b.effdt = b_ed.effdt AND
    b.system_id = b_ed.system_id AND
    b.md_action = b_ed.md_action AND
    b_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY')) AND
    a.group_id = 'PSD01' AND
    a.workorder_no = 'H00034758' AND
    a.assignment_no = 'H00034758-001' AND
    b.system_id = 'PB' AND
    b.md_action = 'EARN_TYPE' AND
    b.value = 'R';
    This one produces the error
    SELECT a.pay_rate, a.bill_rate, a.frequency, c.value
    FROM SYSADM.ps_pb_wkord_sq_rte a, SYSADM.ps_md_erncd_action b,
    SELECT DISTINCT z.value
    FROM SYSADM.ps_md_erncd_action z
    WHERE z.md_action = 'CALC_BURD' AND
    z.system_id = 'PB' AND
    z.erncd = a.erncd AND **This is line in question**
    z.effdt = (
    SELECT MAX(z_ed.effdt)
    FROM SYSADM.ps_md_erncd_action z_ed
    WHERE z.setid = z_ed.setid AND
    z.erncd = z_ed.erncd AND
    z.effdt = z_ed.effdt AND
    z.system_id = z_ed.system_id AND
    z.md_action = z_ed.md_action AND
    z_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY'))) c
    WHERE a.erncd = b.erncd AND
    b.effdt = (
    SELECT MAX(b_ed.effdt)
    FROM SYSADM.ps_md_erncd_action b_ed
    WHERE b.setid = b_ed.setid AND
    b.erncd = b_ed.erncd AND
    b.effdt = b_ed.effdt AND
    b.system_id = b_ed.system_id AND
    b.md_action = b_ed.md_action AND
    b_ed.effdt <= TO_DATE('04/01/2001','MM/DD/YYYY')) AND
    a.group_id = 'PSD01' AND
    a.workorder_no = 'H00034758' AND
    a.assignment_no = 'H00034758-001' AND
    b.system_id = 'PB' AND
    b.md_action = 'EARN_TYPE' AND
    b.value = 'R';
    Any help is greatly appreciated.
    Thanks,
    JD Lippard

    Hi JD,
    your code is very difficult to read to i will give you some general information.
    SELECT t1.c1,t1.c2
    FROM table t1
    , (SELECT t2.col1 alias1
    , t2.col2 alias2
    , a.s.o.
    FROM anytable t2
    ) tablealias
    WHERE t1.c1 = tablealias.alias1
    You can select any columns inside this 'dynamic view' whichever you need for a join. Independent if you print them or not.
    But you cannot join INSIDE this dynamic view to outer tables like
    SELECT t1.c1,t1.c2
    FROM table t1
    , (SELECT t2.col1 alias1
    , t2.col2 alias2
    , a.s.o.
    FROM anytable t2
    WHERE t1.c2 = t2.col2
    ) tablealias
    WHERE bla
    Maybe it helps a bit.
    Cheers,
    Udo

  • Subquery in the Select Clause

    Can a subquery in the select clause return more than one field?
    Something like this:
    select ename,
    (select dname, loc from dept where e.deptno = deptno) as (dname,loc)
    from emp e

    A simple way to find out is to test it. In my tests below, the original query produces an error that says it didn't find FROM where it expected. Eliminating "as (dname,loc)" produces an error about too many values. Putting only one value in the subquery in the select clause works, whether it is dname or loc. Concatenating the two columns as dname || ' ' || loc to produce one value in the subquery in the select clause works. Using two separate subqueries, one for dname and one for loc works. And, lastly, a cursor statement with both values works, although the output is a little hard to read. This may be different in newer versions. I am using Oracle 8.1.7. It may be different in 9i. I was unable to locate any documentation on the cursor statement or cursor operator which I have also heard it called. I only knew to try it because I have seen it used. I looked up the SELECT syntax in the 9i SQL Reference and there was no mention of cursor in the select clause. Can anyone provide a link to some documentation on this? I vaguely recall reading something that said that, other than outputting from SQL*Plus as below, it wasn't yet compatible with anything else, like you can't use it in PL/SQL, but I can't remember where I read it.
    SQL> -- 2 values in subquery in select clause:
    SQL> select ename,
      2  (select dname, loc from dept where e.deptno = deptno) as (dname,loc)
      3  from emp e
      4  /
    (select dname, loc from dept where e.deptno = deptno) as (dname,loc)
    ERROR at line 2:
    ORA-00923: FROM keyword not found where expected
    SQL> select ename,
      2  (select dname, loc from dept where e.deptno = deptno)
      3  from emp e
      4  /
    (select dname, loc from dept where e.deptno = deptno)
    ERROR at line 2:
    ORA-00913: too many values
    SQL> -- 1 value in subquery in select clause:
    SQL> select ename,
      2  (select dname from dept where e.deptno = deptno)
      3  from emp e
      4  /
    ENAME      (SELECTDNAMEFR                                                      
    SMITH      RESEARCH                                                            
    ALLEN      SALES                                                               
    WARD       SALES                                                               
    JONES      RESEARCH                                                            
    MARTIN     SALES                                                               
    BLAKE      SALES                                                               
    CLARK      ACCOUNTING                                                          
    SCOTT      RESEARCH                                                            
    KING       ACCOUNTING                                                          
    TURNER     SALES                                                               
    ADAMS      RESEARCH                                                            
    JAMES      SALES                                                               
    FORD       RESEARCH                                                            
    MILLER     ACCOUNTING                                                          
    14 rows selected.
    SQL> select ename,
      2  (select loc from dept where e.deptno = deptno)
      3  from emp e
      4  /
    ENAME      (SELECTLOCFRO                                                       
    SMITH      DALLAS                                                              
    ALLEN      CHICAGO                                                             
    WARD       CHICAGO                                                             
    JONES      DALLAS                                                              
    MARTIN     CHICAGO                                                             
    BLAKE      CHICAGO                                                             
    CLARK      NEW YORK                                                            
    SCOTT      DALLAS                                                              
    KING       NEW YORK                                                            
    TURNER     CHICAGO                                                             
    ADAMS      DALLAS                                                              
    JAMES      CHICAGO                                                             
    FORD       DALLAS                                                              
    MILLER     NEW YORK                                                            
    14 rows selected.
    SQL> select ename,
      2  (select dname || ' ' || loc from dept where e.deptno = deptno)
      3  from emp e
      4  /
    ENAME      (SELECTDNAME||''||LOCFROMDEP                                        
    SMITH      RESEARCH DALLAS                                                     
    ALLEN      SALES CHICAGO                                                       
    WARD       SALES CHICAGO                                                       
    JONES      RESEARCH DALLAS                                                     
    MARTIN     SALES CHICAGO                                                       
    BLAKE      SALES CHICAGO                                                       
    CLARK      ACCOUNTING NEW YORK                                                 
    SCOTT      RESEARCH DALLAS                                                     
    KING       ACCOUNTING NEW YORK                                                 
    TURNER     SALES CHICAGO                                                       
    ADAMS      RESEARCH DALLAS                                                     
    JAMES      SALES CHICAGO                                                       
    FORD       RESEARCH DALLAS                                                     
    MILLER     ACCOUNTING NEW YORK                                                 
    14 rows selected.
    SQL> select ename,
      2  (select dname from dept where e.deptno = deptno),
      3  (select loc from dept where e.deptno = deptno)
      4  from emp e
      5  /
    ENAME      (SELECTDNAMEFR (SELECTLOCFRO                                        
    SMITH      RESEARCH       DALLAS                                               
    ALLEN      SALES          CHICAGO                                              
    WARD       SALES          CHICAGO                                              
    JONES      RESEARCH       DALLAS                                               
    MARTIN     SALES          CHICAGO                                              
    BLAKE      SALES          CHICAGO                                              
    CLARK      ACCOUNTING     NEW YORK                                             
    SCOTT      RESEARCH       DALLAS                                               
    KING       ACCOUNTING     NEW YORK                                             
    TURNER     SALES          CHICAGO                                              
    ADAMS      RESEARCH       DALLAS                                               
    JAMES      SALES          CHICAGO                                              
    FORD       RESEARCH       DALLAS                                               
    MILLER     ACCOUNTING     NEW YORK                                             
    14 rows selected.
    SQL> -- cursor statement:
    SQL> select ename,
      2  cursor (select dname, loc from dept where e.deptno = deptno)
      3  from emp e
      4  /
    ENAME      CURSOR(SELECTDNAME,L                                                
    SMITH      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    ALLEN      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    WARD       CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    JONES      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    MARTIN     CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    BLAKE      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    CLARK      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    ACCOUNTING     NEW YORK                                                        
    1 row selected.
    SCOTT      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    KING       CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    ACCOUNTING     NEW YORK                                                        
    1 row selected.
    TURNER     CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    ADAMS      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    JAMES      CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    SALES          CHICAGO                                                         
    1 row selected.
    FORD       CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    RESEARCH       DALLAS                                                          
    1 row selected.
    MILLER     CURSOR STATEMENT : 2                                                
    CURSOR STATEMENT : 2
    DNAME          LOC                                                             
    ACCOUNTING     NEW YORK                                                        
    1 row selected.
    14 rows selected.

  • Use of Where and having clause

    Hi all,
    I always have a doubt about use of HAVING and WHERE clause,
    suppose I have table T1 with only one column C1
    CREATE TABLE T1
    (C1 VARCHAR2(1) );
    which having data by following INSERT scripts
    INSERT INTO T1 VALUES('A');
    INSERT INTO T1 VALUES('B');
    INSERT INTO T1 VALUES('C');
    INSERT INTO T1 VALUES('A');
    INSERT INTO T1 VALUES('B');
    INSERT INTO T1 VALUES('A');
    Now I want result as follows
    C1 ==== COUNT(C1)
    ==============
    B ===== 2
    A ===== 3
    So out of query 1 and 2 which approach is right ?
    1) SELECT C1,COUNT(C1) FROM T1
    WHERE C1<>'C'
    GROUP BY C1
    ORDER BY C1 DESC;
    2) SELECT C1,COUNT(C1) FROM T1
    GROUP BY C1
    HAVING C1<>'C'
    ORDER BY C1 DESC;
    Edited by: user13306874 on Jun 21, 2010 2:36 AM

    In SQL, it's always best to filter data at the earliest moment possible.
    In your example the WHERE clause would be that moment:
    SQL> explain plan for
      2  select c1,count(c1)
      3  from t1
      4  where c1 != 'C'
      5  group by c1
      6* order by c1 desc;
    Explained.
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 3946799371
    | Id  | Operation          | Name | Rows  | Bytes |
    |   0 | SELECT STATEMENT   |      |     5 |    10 |
    |   1 |  SORT GROUP BY     |      |     5 |    10 |
    |*  2 |   TABLE ACCESS FULL| T1   |     5 |    10 |
    Predicate Information (identified by operation id):
       2 - filter("C1"!='C')
    18 rows selected.
    SQL>As you can see the filter is applied during the scan of T1.
    Whereas in the HAVING case:
    SQL> explain plan for
      2  select c1,count(c1)
      3  from t1
      4  group by c1
      5  having c1 != 'C'
      6* order by c1 desc;
    Explained.
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 3146800528
    | Id  | Operation           | Name | Rows  | Bytes |
    |   0 | SELECT STATEMENT    |      |     6 |    12 |
    |*  1 |  FILTER             |      |       |       |
    |   2 |   SORT GROUP BY     |      |     6 |    12 |
    |   3 |    TABLE ACCESS FULL| T1   |     6 |    12 |
    Predicate Information (identified by operation id):
       1 - filter("C1"!='C')
    18 rows selected.
    SQL>The scan is done after all groups have been computed: one of which was computed in vain, since it will be filtered away due to the HAVING clause.
    In general I would use as a guideline: if you are not using aggregate functions in your HAVING clause predicate, then move that predicate to the WHERE portion of your query.
    Edited by: Toon Koppelaars on Jun 21, 2010 11:54 AM

  • Select stmts with Having Clause

    Hi,
    Can some body help me to improve the performance of the below query...
    select t.seq_no,t.contract_id,t.date_from from test_plan_tab t
    group by t.seq_no,t.contract_id,t.date_from
    having (select count(*)
    from test_plan_tab p
    where p.contract_id = t.contract_id
    and p.date_from = t.date_from) > 1
    The having clause will reduce the performance of the above query I guess...
    Thanks And Best Regards,
    /Dinesh...

    If Seq_no is unique then try this
    SELECT MIN(t.seq_no),contract_id,t.date_from,count(*) from test_plan_tab t
    group by t.contract_id,t.date_from
    HAVING COUNT(*) > 1or
    you can try as fsitja said, but you can omit the group by as the partition has already been done on grouping columns
    SELECT seq_no, contract_id, date_from
      FROM (SELECT t.seq_no, t.contract_id, t.date_from, COUNT(*) over(PARTITION BY contract_id, date_from) tot
              FROM test_plan_tab t)
    WHERE tot > 1Regards,
    Prazy

  • Group By -- Having Clause related doubt.

    Hello,
    Can we Write/Use rather a 'Having Condition' Before a Group by Clause ..?
    If Yes then How does it Work.. I mean a 'Having' is a WHERE clause (filter) on Aggregate results ...
    SO how does Having works before grouping the Results..??

    Hi,
    Aijaz Mallick wrote:
    Hello,
    Can we Write/Use rather a 'Having Condition' Before a Group by Clause ..?What happens when you try it?
    If Yes then How does it Work.. I mean a 'Having' is a WHERE clause (filter) on Aggregate results ... Right; the HAVING clause is like another WHERE clause.
    The WHERE clause is applied before the GROUP BY is done, and the aggregate functions are computed.
    The HAVING clause is applied after the GROUP BY is done, and the aggregate functions are computed, so you can use aggregate functions in the HAVING clause.
    SO how does Having works before grouping the Results..??The order in which clauses appear in your code isn't necessarily the order in which they are performed. For example,
    SELECT    job
    ,         COUNT (*)  AS cnt
    FROM      scott.emp
    GROUP BY  job;Does it confuse you that this query can reference COUNT (*) in the SLECT clause, which is before the GROUP BY clause?
    The SELECT clause which always comes before the GROUP BY clause in code. That does not mean that the SELECT clause is completed before the GROUP BY clause is begun.
    If the documentation says that clauses must be in a certain order, then use that order, even if your current version of Oracle allows them to be in a different order. There's no guarantee that the next version of Oracle will allow something that was always said to be wrong.

  • How to have Having clause in Group by

    Hi All,
    While using aggregated function (max,min etc) on columns, the SQL generated automatically has the non aggregated columns in the group by clause. How to specify the Having condition ?
    select a , max(b)
    from t
    group by a
    having <condition>
    TIA...

    Hi,
    In your interface drag and drop the source column into canvas for which you want to generate the HAVING clause.
    It will create filters for those columns .Now use aggregation functions like SUM, MAX,MIN, AVG etc in that filter query .
    The code generated will now contain the HAVING clause in it .
    Thanks,
    Sutirtha

  • Group by clause and having clause in select

    hi frnds
    plz give me some information of group by and having clause used in select statement with example
    thanks

    The Open SQL statement for reading data from database tables is:
    SELECT      <result>
      INTO      <target>
      FROM      <source>
      [WHERE    <condition>]
      [GROUP BY <fields>]
      [HAVING   <cond>]
      [ORDER BY <fields>].
    The SELECT statement is divided into a series of simple clauses, each of which has a different part to play in selecting, placing, and arranging the data from the database.
    You can only use the HAVING clause in conjunction with the GROUP BY clause.
    To select line groups, use:
    SELECT <lines> <s1> [AS <a1>] <s2> [AS <a2>] ...
                   <agg> <sm> [AS <am>] <agg> <sn> [AS <an>] ...
           GROUP BY <s1> <s2> ....
           HAVING <cond>.
    The conditions <cond> that you can use in the HAVING clause are the same as those in the SELECT clause, with the restrictions that you can only use columns from the SELECT clause, and not all of the columns from the database tables in the FROM clause. If you use an invalid column, a runtime error results.
    On the other hand, you can enter aggregate expressions for all columns read from the database table that do not appear in the GROUP BY clause. This means that you can use aggregate expressions, even if they do not appear in the SELECT clause. You cannot use aggregate expressions in the conditions in the WHERE clause.
    As in the WHERE clause, you can specify the conditions in the HAVING clause as the contents of an internal table with line type C and length 72.
    Example
    DATA WA TYPE SFLIGHT.
    SELECT   CONNID
    INTO     WA-CONNID
    FROM     SFLIGHT
    WHERE    CARRID = 'LH'
    GROUP BY CONNID
    HAVING   SUM( SEATSOCC ) > 300.
      WRITE: / WA-CARRID, WA-CONNID.
    ENDSELECT.
    This example selects groups of lines from database table SFLIGHT with the value ‘LH’ for CARRID and identical values of CONNID. The groups are then restricted further by the condition that the sum of the contents of the column SEATSOCC for a group must be greater than 300.
    The <b>GROUP BY</b> clause summarizes several lines from the database table into a single line of the selection.
    The GROUP BY clause allows you to summarize lines that have the same content in particular columns. Aggregate functions are applied to the other columns. You can specify the columns in the GROUP BY clause either statically or dynamically.
    Specifying Columns Statically
    To specify the columns in the GROUP BY clause statically, use:
    SELECT <lines> <s1> [AS <a 1>] <s 2> [AS <a 2>] ...
                   <agg> <sm> [AS <a m>] <agg> <s n> [AS <a n>] ...
           GROUP BY <s1> <s 2> ....
    To use the GROUP BY clause, you must specify all of the relevant columns in the SELECT clause. In the GROUP BY clause, you list the field names of the columns whose contents must be the same. You can only use the field names as they appear in the database table. Alias names from the SELECT clause are not allowed.
    All columns of the SELECT clause that are not listed in the GROUP BY clause must be included in aggregate functions. This defines how the contents of these columns is calculated when the lines are summarized.
    Specifying Columns Dynamically
    To specify the columns in the GROUP BY clause dynamically, use:
    ... GROUP BY (<itab>) ...
    where <itab> is an internal table with line type C and maximum length 72 characters containing the column names <s 1 > <s 2 > .....
    Example
    DATA: CARRID TYPE SFLIGHT-CARRID,
          MINIMUM TYPE P DECIMALS 2,
          MAXIMUM TYPE P DECIMALS 2.
    SELECT   CARRID MIN( PRICE ) MAX( PRICE )
    INTO     (CARRID, MINIMUM, MAXIMUM)
    FROM     SFLIGHT
    GROUP BY CARRID.
      WRITE: / CARRID, MINIMUM, MAXIMUM.
    ENDSELECT.
    regards
    vinod

  • HAVING clause error in JPA 2 examples

    In Chapter 8: Query Language of the Pro JPA 2 Mastering the Java Persistence API book, the jpqlExamples WAR has this query:
    SELECT e, COUNT(p)
    FROM Employee e JOIN e.projects p
    GROUP BY e
    HAVING COUNT(p) >= 2
    When executed, the following error occurs:
    java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
    Exception Description: Error compiling the query [SELECT e, COUNT(p) FROM Employee e JOIN e.projects p GROUP BY e HAVING COUNT(p) >= 2], line 1, column 80: invalid HAVING expression [COUNT(p) >= 2] for query with grouping [GROUP BY e]. The HAVING clause must specify search conditions over the grouping items or aggregate functions that apply to grouping items.
    I bring this us because I have an application which is getting the same error and need a fix. If the query is indeed legal in JPA 2, then why the error? If if it is my setup however, then I would like suggestions on fixing it. I am using GlassFish v3 (build 74.2), updated regularly with the Update Tool.

    The bug has been reopened. Now it says:
    Reopening because there is some debate about whether this should be supported
    by the spec. Some people read the spec to say the above query is allowed - I
    am not convinced, but discussion can be appended to this bug if necessary.
    This is Bug 308482, and I assume at least a few might want to take a look.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=308482

  • Why Scalar Subquery expression cannot be used in HAVING clauses?

    Hi All,
    I'm new to SQL. I'm confused with Scalar Subquery.
    Is there anyone who can answer me why Scalar Subquery expression cannot be used in HAVING clauses.
    Can you show me a example?
    Thanks very much,
    Xianyi.Ye
    Edited by: 908428 on 2012-1-16 下午7:24

    Hi,
    908428 wrote:
    Hi Frank,
    Thank you for your quick reply. I also agree with your point.
    But when I read the book, "OCA Oracle Database SQL Certified Expert Exam Guide",( link to illegal copies of book removed by moderator )
    on Page 359, it said that
    Scalar subquery expressions cannot be used in the following locations:
    1. In CHECK constraints
    2. In GROUP BY clauses
    3. In HAVING clauses
    4. In a function-based index (which is coming up in Chapter 11)
    5. As a DEFAULT value for a column
    6. In the RETURNING clause of any DML statement
    7. In the WHEN conditions of CASE
    8. In the START WITH and CONNECT BY clauses, which we discuss in
    Chapter 16.7 and 8 are wrong. Scalar sub-queries can be used in WHEN conditions and START WITH and CONNECT BY clauses. (At least in Oracle 10.2. Is the book based on some earlier version?)
    Edited by: BluShadow on 17-Jan-2012 09:08

  • This novice is having trouble with the AS clause...

    I appreciate any help I can get.  As you will probably be able to tell when I ask my question, I am a complete newbie when it comes to SQL.  I just started a class in Database Design and I am already stuck. 
    Anyway, my question is this: why am I getting an error message when I execute my query?  I hope I am providing all the necessary information.  This is my SELECT statement:
    SELECT ItemID, ItemPrice, DiscountAmount, Quantity, (ItemPrice * Quantity) AS [PriceTotal], (DiscountAmount * Quantity)
    AS [DiscountTotal], ((ItemPrice-DiscountAmount) * Quantity) AS [ItemTotal]
    FROM OrderItems
    WHERE ItemTotal > 500
    ORDER BY ItemTotal DESC
    And this is the question asked of me:
    Write a SELECT statement that returns these column names and data from the OrderItems table:
    ItemID...........................The ItemID column
    ItemPrice.......................The ItemPrice column
    DiscountAmount...........The DiscountAmount column
    Quantity.........................The Quantity column
    PriceTotal.......................A column that’s calculated by multiplying the item price with the
    quantity
    DiscountTotal.................A column that’s calculated by multiplying the discount amount
    with the quantity
    ItemTotal........................A column that’s calculated by subtracting the discount amount from the item price and then multiplying by the quantity
    Only return rows where the ItemTotal is greater than 500.
    Sort the result set by item total in descending sequence.
    I can tell the issue is with the ItemTotal column I created in my SELECT statement, but I don't know how to fix it.  I could very well be wrong, but I thought that when I declared a temporary column using the AS clause, that I could use the title of
    that column for the rest of the statement.  I don't know how to post the database I am using on here, so I hope you don't need that.  Oh, but when I execute the statement, the message says that the ItemTotal column doesn't exist.  And when I
    comment out the WHERE clause in my statement, it works fine.
    Sorry for the long winded question and I eagerly away any help I can get.  Thanks!

    Hi,
    Derived tables can be used instead as well like so
    Select * FROM( SELECT ItemID, ItemPrice, DiscountAmount, Quantity, (ItemPrice * Quantity) AS [PriceTotal], (DiscountAmount * Quantity)
    AS [DiscountTotal], ((ItemPrice-DiscountAmount) * Quantity) AS [ItemTotal]
    FROM OrderItems) mytable
    WHERE [ItemTotal] > 500
    ORDER BY [ItemTotal] DESC
    Hope this helps
    Thanks
    Bhanu

  • Urgent Group by Having Clause Fails in Oracle and Works in Sybase

    Hello EveryBody I need to select curve data of curve whose date is maximum in that curve so say if i ahve
    so if records are
    curveid curvename curvedate
    1001 test1 12/12/1003
    1001 test1 12/13/1003
    1002 test2 12/12/2002
    1002 test2 12/12/2004
    I have query which run well in sybase but oracle screw up...My logic say having clause is use to filter the records of group so it should have worked in oracle.....
    Here is query
    select curveid,curvename from curve group by curveid having curvedate =max(curve_date)
    This give "not a Group by " error in oracle....It work well in sybase...
    ORA-00979: not a GROUP BY expression
    I have query which use subquery to select these records but i don't want that to use that query
    Please help

    please understand what I need the result
    for each curve i need that data of that curve who date is max in that curve group
    so say for 1001 there are two date 1/1/2001 and 1/1/2002
    I need the data of curve 1001 with date 1/1/2002
    Oracle should have some alternative solution for this....
    If i have to use subquery I do have subquery
    select a.curveid, b.curvename from curve a group by curveid having curvedate = (select max(curvedate) from curve where a.curveid=b.curveid group by curveid );
    I don't want to use that ,,,
    I want to solve my probelm using having and group/....
    Main purpose of having is to filter the records from group result so IT SHOULD DO THAT WHY ORACLE GIVE ORA ERROR FOR
    group by curve_id having curve_date=max(curve_date)
    Creators of oracle please reply

  • Subquery in dynamic where-clause

    Hi,
    i'm trying to build a dynamic sql-statement in OPEN SQL, which uses a subquery in the dynamic where-clause.
    In the following example code the first select works fine, the second one raises an error.
    report  zerrorforum.
    data:
      l_var_anzahl
    * No Error
    select
       count(*)
    into
       l_var_anzahl
    from
       t000 as t1
    where
       t1~mandt in ( select t2~mandt from t000 as t2 where t2~mandt = t1~mandt ).
    * Error
    select
       count(*)
    into
       l_var_anzahl
    from
       t000 as t1
    where
       ('T1~MANDT IN ( SELECT T2~MANDT FROM T000 AS T2 WHERE T2~MANDT = T1~MANDT )').
    The Error Analysis says the following:
    The exception, which is assigned to class 'CX_SY_DYNAMIC_OSQL_SEMANTICS', was
    not caught and therefore caused a runtime error.  The reason for the exception is:
    The current ABAP program has tried to execute an Open SQL statement
    which contains a WHERE, ON or HAVING condition with a dynamic part.
    The part of the WHERE, ON or HAVING condition specified at runtime in
    a field or an internal table, contains the invalid value "SELECT".
    Is this behaviour documented anywhere? I didn´t find anything.
    Or is it a bug?
    Klaus-Dieter Lueppens

    Hi,
    it's not possible. Here is a quote from ABAP documentation from dynamic WHERE condition.
    A logical expression can be specified as a parenthesized data object cond_syntax that contains the syntax of a logical expression or is initial when the statement is executed. It has been possible since SAP Web AS 6.40 to specify all logical expressions dynamically, with the exception of the evaluation of a subquery.
    Cheers

  • Is there a way to use dynamic built string in the "from" clause

    Hi all, im having one problem and now, im not sure how to solve it easily at all... :) Is there someone that would be so kind and put a eye on it? ..thx
    I have plsql proc, in which i have a list of table_names. For each of that table i need to run a query that will retrieve me a list of values and for each of that value i need to do something.
    If i can be more specific about the problem -> each of that table is built as key_column, value_columns, day,starttime. For a key per table there are 4 records per hour - every quarter. Im truncating those quarters to full-quarter (minutes => 0->14 = 0min; 15->29 = 15min, 30->44 = 30, 45->59=45)
    example
    i get for one key and specific hour four records at 15:01;15:16;15:31;15:46 => i truncate em to 15:00;15:15;15:30;15:45..Sometimes there is a problem with the tool that is generating those data for me, and one quarter could be moved a little - so i get data like 15:01;15:16;15:29;15:46 => after i truncate the times i get duplicates in second quarter. It also can happen like this : 23:00; 23:14; 23:29; 23:44; 23:59 => totaly bad => cos the last one supposed to be as 0:00 next day, ..and 23:14 as 23:15...So...that was a problem - and solution -> i wanted to create plsql that will find those hours in each table i ve defined, and for each problem hour i make some fixes - update the bad time ...
    ..and i have problem - can i put an dynamic built table_name in the "from" clause?
    example how i wanted to do that:
    declare
         type t_objectName     is table of varchar2(030) index     by pls_integer;
         l_tableName              t_objectName;
    begin
    l_tableName(1) := 'tmphlrgl';
    l_tableName(2) := 'tmprcfgl';
    l_tableName(3) := 'tmprcfbs';
    l_tableName(4) := 'tmpvlrgl';
    for i in (select evtime from (select day,trunc_quarter(evtime) evtime,m_id from l_tableName(i) group by day,trunc_quarter(evtime),m_id having count(*)>1) order by evtime) loop
    --some other conditions and the update...
    end loop;
    end;
    /I cannot use the l_tableName(i) for FROM ...get an error...I was thinking to build it as dynamic sql and execute immediate into some kind of object that can store mutliple lines, from which i would in the FOR cycle get the data...But im not sure if this could be done in plsql...
    thanks for your time and help..
    d.

    declare
    c sys_refcursor;
    begin
    for i in 1..4 loop
    open c for 'day,trunc_quarter(evtime) evtime,m_id
    from ' || l_tableName(i) ||
    'group by day,trunc_quarter(evtime),m_id having
    count(*)>1) order by evtime';Just to high light SELECT is missing that all
    OPEN c FOR ' SELECT day,trunc_quarter(evtime) evtime,m_id
              FROM' || l_tableName(i) ||
    'GROUP BY day,trunc_quarter(evtime),m_id  HAVING  count(*)>1)   ORDER BY evtime';

Maybe you are looking for