Query, Having clause

I have a test data, like this
with t as (
select 1 tp, 0 sm_1, 1 sm_2, 'a' code from dual
union all
select 1 tp, 0 sm_1, 2 sm_2, 'b' from dual
union all
select 2 tp, 3 sm_1, 0 sm_2, 'c' from dual
union all
select 3 tp, 0 sm_1, 2 sm_2, 'a' from dual
union all
select 4 tp, 0 sm_1, 1 sm_2, 'a' from dual
union all
select 4 tp, 2 sm_1, 3 sm_2,'b' from dual
union all
select 4 tp, 2 sm_1, 3 sm_2, 'c' from dual
union all
select 5 tp, 0 sm_1, 0 sm_2, 'a' from dual
union all
select 5 tp, 0 sm_1, 0 sm_2, 'b' from dual
union all
select 5 tp, 0 sm_1, 0 sm_2, 'c' from dual)
SQL> with t as (
2 select 1 tp, 0 sm_1, 1 sm_2, 'a' code from dual
3 union all
4 select 1 tp, 0 sm_1, 2 sm_2, 'b' from dual
5 union all
6 select 2 tp, 3 sm_1, 0 sm_2, 'c' from dual
7 union all
8 select 3 tp, 0 sm_1, 2 sm_2, 'a' from dual
9 union all
10 select 4 tp, 0 sm_1, 1 sm_2, 'a' from dual
11 union all
12 select 4 tp, 2 sm_1, 3 sm_2,'b' from dual
13 union all
14 select 4 tp, 2 sm_1, 3 sm_2, 'c' from dual
15 union all
16 select 5 tp, 0 sm_1, 0 sm_2, 'a' from dual
17 union all
18 select 5 tp, 0 sm_1, 0 sm_2, 'b' from dual
19 union all
20 select 5 tp, 0 sm_1, 0 sm_2, 'c' from dual)
21 select tp, SUM(sm_1), SUM(sm_2), code from t
22 group by tp, code
23 /
TP SUM(SM_1) SUM(SM_2) CODE
1 0 1 a
1 0 2 b
2 3 0 c
3 0 2 a
4 0 1 a
4 2 3 b
4 2 3 c
5 0 0 a
5 0 0 b
5 0 0 c
10 rows selected
SQL>
And I want to get this result
TP SUM(SM_1) SUM(SM_2) CODE
1 0 1 a
1 0 2 b
2 3 0 c
3 0 2 a
4 0 1 a
4 2 3 b
4 2 3 c
5 0 0 a
E.g. if SM_1 = SM_2(all of the rows) In group of tp, then return random rows with tp = 5, if
5 0 0 c
5 1 2 a
5 3 1 b
then return
5 1 2 a
5 3 1 b
And I don't undersatnd how it's do with Having Clause.
Thank you!

SQL> with t as (
  2     select 1 tp, 0 sm_1, 1 sm_2, 'a' code from dual
  3     union all
  4     select 1 tp, 0 sm_1, 2 sm_2, 'b' from dual
  5     union all
  6     select 2 tp, 3 sm_1, 0 sm_2, 'c' from dual
  7     union all
  8     select 3 tp, 0 sm_1, 2 sm_2, 'a' from dual
  9     union all
10     select 4 tp, 0 sm_1, 1 sm_2, 'a' from dual
11     union all
12     select 4 tp, 2 sm_1, 3 sm_2,'b' from dual
13     union all
14     select 4 tp, 2 sm_1, 3 sm_2, 'c' from dual
15     union all
16 select 5 tp, 0 sm_1, 0 sm_2, 'a' from dual
17 union all
18 select 5 tp, 0 sm_1, 0 sm_2, 'b' from dual
19 union all
20 select 5 tp, 0 sm_1, 0 sm_2, 'c' from dual)
21  select tp, sm_1, sm_2, code
22  from   (select tp,
23                 SUM(sm_1) sm_1,
24                 SUM(sm_2) sm_2,
25                 code,
26                 count(*) over (partition by tp) ct_tp,
27                 count(*) over (partition by tp, SUM(sm_1), SUM(sm_2)) ct,
28                 row_number() over (partition by tp order by null) rn
29          from t
30          group by tp, code)
31  where   decode(ct,ct_tp,rn,1)=1
32  and     case when sm_1 = 0 and sm_2 = 0 and ct_tp-ct > 0 then 0 else 1 end = 1;
        TP       SM_1       SM_2 C
         1          0          1 a
         1          0          2 b
         2          3          0 c
         3          0          2 a
         4          0          1 a
         4          2          3 b
         4          2          3 c
5 0 0 a
8 rows selected.
SQL> with t as (
  2     select 1 tp, 0 sm_1, 1 sm_2, 'a' code from dual
  3     union all
  4     select 1 tp, 0 sm_1, 2 sm_2, 'b' from dual
  5     union all
  6     select 2 tp, 3 sm_1, 0 sm_2, 'c' from dual
  7     union all
  8     select 3 tp, 0 sm_1, 2 sm_2, 'a' from dual
  9     union all
10     select 4 tp, 0 sm_1, 1 sm_2, 'a' from dual
11     union all
12     select 4 tp, 2 sm_1, 3 sm_2,'b' from dual
13     union all
14     select 4 tp, 2 sm_1, 3 sm_2, 'c' from dual
15     union all
16 select 5 tp, 0 sm_1, 0 sm_2, 'a' from dual
17 union all
18 select 5 tp, 1 sm_1, 0 sm_2, 'b' from dual
19 union all
20 select 5 tp, 2 sm_1, 0 sm_2, 'c' from dual)
21  select tp, sm_1, sm_2, code
22  from   (select tp,
23                 SUM(sm_1) sm_1,
24                 SUM(sm_2) sm_2,
25                 code,
26                 count(*) over (partition by tp) ct_tp,
27                 count(*) over (partition by tp, SUM(sm_1), SUM(sm_2)) ct,
28                 row_number() over (partition by tp order by null) rn
29          from t
30          group by tp, code)
31  where   decode(ct,ct_tp,rn,1)=1
32  and     case when sm_1 = 0 and sm_2 = 0 and ct_tp-ct > 0 then 0 else 1 end = 1;
        TP       SM_1       SM_2 C
         1          0          1 a
         1          0          2 b
         2          3          0 c
         3          0          2 a
         4          0          1 a
         4          2          3 b
         4          2          3 c
5 1 0 b
5 2 0 c
9 rows selected.Nicolas.

Similar Messages

  • How to Use SQL Query having IN Clause With DB Adapter

    Hi,
    I am using 11.1.1.5 want to find out how to Use SQL Query having IN Clause With DB Adapter. I want to pass the IN values dynamically. Any ideas.
    Thanks

    invoke a stored procedure, it's safer than trying to put together an arbitrary SQL statement in the JCA adapter

  • 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

  • Direct Execution of query having Unicode Characters

    Direct Execution of query having Unicode Characters
    Hi All,
    In my application I am firing a Select Query having Unicode characters in Where Clause under condition like '%%'
    to Oracle 10g DB from a Interface written in VC6.0...
    Application funcationality is working fine for ANSI characters and getting the result of Select properly.
    But in case of Unicode Characters in VC it says 'No Data Found'.
    I know where the exact problem is in my code. But not getting the exact solution for resolving my issue...
    Here with I am adding my code snippet with the comments of what i understand and what i want to understand...
    DBPROCESS Structure used in the functions,_
    typedef struct
    HENV hEnv;
    HDBC hDbc;
    HSTMT hStmt;
    char CmdBuff[[8192]];
    char RpcParamName[[255]];
    SQLINTEGER SpRetVal;
    SQLINTEGER ColIndPtr[[255]];
    SQLINTEGER ParamIndPtr[[255]];
    SQLPOINTER pOutputParam;
    SQLUSMALLINT CurrentParamNo;
    SQLUSMALLINT OutputParamNo;
    SQLUSMALLINT InputParamCtr;
    SQLINTEGER BatchStmtNo;
    SQLINTEGER CmdBuffLen;
    short CurrentStmtType;
    SQLRETURN LastStmtRetcode;
    SQLCHAR SqlState[[10]];
    int ShowDebug;
    SQLCHAR* ParameterValuePtr;
    int ColumnSize;
    DBTYPE DatabaseType;
    DRVTYPE OdbcDriverType;
    BLOCKBIND *ptrBlockBind;
    } DBPROCESS;
    BOOL CDynamicPickList::GetResultSet(DBPROCESS *pDBProc, bstrt& pQuery, short pNumOdbcBindParams, COdbcBindParameter pOdbcBindParams[], CQueryResultSet& pQueryResultSet)
         int               lRetVal,
                        lNumRows;
         bstrt               lResultSet;
         wchar_t               lColName[[256]];     
         SQLUINTEGER          lColSize;
         SQLSMALLINT          lColNameLen,
                        lColDataType,
                        lColNullable,
                        lColDecDigits,                         
                        lNumResultCols;
         wchar_t               lResultRow[[32]][[256]];
    OdbcCmdW(pDBProc, (wchar_t *)pQuery); *//Query is perfectly fine till this point all the Unicode Characters are preserved...*
         if ( OdbcSqlExec(pDBProc) != SUCCEED )
              LogAppError(L"Error In Executing Query %s", (wchar_t *)pQuery);          
              return FALSE;
    Function OdbcCmdW_
    //From this point have no idea what is exactly happening to the Unicode Characters...
    //Actually i have try printing the query that gets stored in CmdBuff... it show junk for Unicode Characters...
    //CmdBuff is the Char type Variable and hence must be showing junk for Unicode data
    //I have also try printing the HexaDecimal of the query... I m not getting the proper output... But till i Understand, I think the HexaDecimal Value is perfect & preserved
    //After the execution of this function the call goes to OdbcSqlExec where actual execution of qurey takes place on DB
    SQLRETURN OdbcCmdW( DBPROCESS p_ptr_dbproc, WCHAR      p_sql_command )
         char *p_sql_commandMBCS;
         int l_ret_val;
         int l_size = wcslen(p_sql_command);
         int l_org_length,
    l_newcmd_length;
    p_sql_commandMBCS = (char *)calloc(sizeof(char) * MAX_CMD_BUFF,1);
    l_ret_val = WideCharToMultiByte(
                        CP_UTF8,
                        NULL,                         // performance and mapping flags
                        p_sql_command,          // wide-character string
                        -1,                         // number of chars in string
                        (LPSTR)p_sql_commandMBCS,// buffer for new string
                        MAX_CMD_BUFF,                    // size of buffer
                        NULL, // default for unmappable chars
                        NULL // set when default char used
    l_org_length = p_ptr_dbproc->CmdBuffLen;
    l_newcmd_length = strlen(p_sql_commandMBCS);
    p_ptr_dbproc->CmdBuff[[l_org_length]] = '\0';
    if( l_org_length )
    l_org_length++;
    if( (l_org_length + l_newcmd_length) >= MAX_CMD_BUFF )
    if( l_org_length == 0 )
    OdbcReuseStmtHandle( p_ptr_dbproc );
    else
    strcat(p_ptr_dbproc->CmdBuff, " ");
         l_org_length +=2;
    strcat(p_ptr_dbproc->CmdBuff, p_sql_commandMBCS);
    p_ptr_dbproc->CmdBuffLen = l_org_length + l_newcmd_length;
    if (p_sql_commandMBCS != NULL)
         free(p_sql_commandMBCS);
    return( SUCCEED );
    Function OdbcSqlExec_
    //SQLExecDirect Requires data of Unsigned Char type. Thus the above process is valid...
    //But i am not getting what is the exact problem...
    SQLRETURN OdbcSqlExec( DBPROCESS *p_ptr_dbproc )
    SQLRETURN l_ret_val;
    SQLINTEGER l_db_error_code=0;
         int     i,l_occur = 1;
         char     *token_list[[50]][[2]] =
    {     /*"to_date(","convert(datetime,",
                                       "'yyyy-mm-dd hh24:mi:ss'","1",*/
                                       "nvl","isnull" ,
                                       "to_number(","convert(int,",
                                       /*"to_char(","convert(char,",*/
                                       /*"'yyyymmdd'","112",
                                       "'hh24miss'","108",*/
                                       "sysdate",     "getdate()",
                                       "format_date", "dbo.format_date",
                                       "format_amount", "dbo.format_amount",
                                       "to_char","dbo.to_char",
                                       "to_date", "dbo.to_date",
                                       "unique","distinct",
                                       "\0","\0"};
    char          *l_qry_lwr;  
    l_qry_lwr = (char *)calloc(sizeof(char) * (MAX_CMD_BUFF), 1);
    l_ret_val = SQLExecDirect( p_ptr_dbproc->hStmt,
    (SQLCHAR *)p_ptr_dbproc->CmdBuff,
    SQL_NTS );
    switch( l_ret_val )
    case SQL_SUCCESS :
    case SQL_NO_DATA :
    ClearCmdBuff( p_ptr_dbproc );
    p_ptr_dbproc->LastStmtRetcode = l_ret_val;
    if (l_qry_lwr != NULL)
         free(l_qry_lwr);
    return( SUCCEED );
    case SQL_NEED_DATA :
    case SQL_ERROR :
    case SQL_SUCCESS_WITH_INFO :
    case SQL_STILL_EXECUTING :
    case SQL_INVALID_HANDLE :
    I do not see much issue in the code... The process flow is quite valid...
    But now i am not getting whether,
    1) storing the string in CmdBuff is creating issue
    2) SQLExecDirect si creating an issue(and some other function can be used here)...
    3) Odbc Driver creating an issue and want some Client Setting to be done(though i have tried doing some permutation combination)...
    Any kind of help would be appreciated,
    Thanks & Regards,
    Pratik
    Edited by: prats on Feb 27, 2009 12:57 PM

    Hey Sergiusz,
    You were bang on target...
    Though it took some time for me to resolve the issue...
    to use SQLExecDirectW I need my query in SQLWCHAR *, which is stored in char * in my case...
    So i converted the incoming query using MultibyteToWideChar Conversion with CodePage as CP_UTF8 and
    then passed it on to SQLExecDirectW...
    It solved my problem
    Thanks,
    Pratik...
    Edited by: prats on Mar 3, 2009 2:41 PM

  • 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

  • Having clause with Analytic function

    can you pls let me know if we can use HAVING clause with analytic function
    select eid,empno,sum(sal) over(partition by year)
    from employee
    where dept = 'SALES'
    having sum(sal) > 10000I m getting error while using the above,
    IS that we can use HAVING clause with partition by
    Thanks in advance

    Your having clause isn't using an analytical function, is using a regular aggregate function.
    You also can't use analytical functions in the where clause or having clause like that as they are windowing functions and belong at the top of the query.
    You would have to wrap the query to achieve what you want e.g.
    SQL> ed
    Wrote file afiedt.buf
      1  select deptno, total_sal
      2  from (
      3        select deptno,sum(sal) over (partition by deptno) as total_sal
      4        from   emp
      5       )
      6  group by deptno, total_sal
      7* having total_sal > 10000
    SQL> /
        DEPTNO  TOTAL_SAL
            20      10875
    SQL>

  • HAVING clause, or ORDER BY clause ....ERROR

    hi i have following query which throws error plz find the solution for the query to go safe..
    Select C.src_cd,
    D.src_nm,
    count(*) supp_clm_count,
    (CASE WHEN A.clm_ttladjamt > 0 then A.clm_ttladjamt else A.clm_ttlreqamt END) as amount
    From IWOWNER.WC_clm A,
    IWOWNER.WC_clm_srvc B,
    SHOWNER.WC_SRC C,
    SHOWNER.WC_SRC_lang D
    where A.clm_id = B.clm_id
    and A.rcv_loc_id = C.src_id
    and C.src_id = D.src_id
    and TRANSLATE(A.clm_rqst_type_cd) = 'SUPPLIERCLAIM'
    and TRANSLATE(A.clm_typ_cd) in ('WARRANTY','PRE-DELIVERY')
    and DATE(A.clm_create_dt) between '01/01/2000' and '01/01/2010'
    Group by C.src_cd, D.src_nm
    ERROR:
    SQLSTATE: 42803, SQLERRMC: CLM_TTLADJAMT
    Message: An expression starting with "CLM_TTLADJAMT" specified in a SELECT clause, HAVING clause, or ORDER BY clause is not specified in the GROUP BY clause or it is in a SELECT clause, HAVING clause, or ORDER BY clause with a column function and no GROUP BY clause is specified

    Hi,
    With analytic function
    /* Formatted on 2009/07/22 10:47 (Formatter Plus v4.8.8) */
    SELECT DISTINCT c.src_cd, d.src_nm,
                    COUNT (1) OVER (PARTITION BY c.src_cd, d.src_nm)
                                                                   supp_clm_count,
                    SUM (CASE
                            WHEN a.clm_ttladjamt > 0
                               THEN a.clm_ttladjamt
                            ELSE a.clm_ttlreqamt
                         END
                        ) OVER (PARTITION BY c.src_cd, d.src_nm) AS amount
               FROM iwowner.wc_clm a,
                    iwowner.wc_clm_srvc b,
                    showner.wc_src c,
                    showner.wc_src_lang d
              WHERE a.clm_id = b.clm_id
                AND a.rcv_loc_id = c.src_id
                AND c.src_id = d.src_id
                AND a.clm_rqst_type_cd = 'SUPPLIERCLAIM'
                AND a.clm_typ_cd IN ('WARRANTY', 'PRE-DELIVERY')
                AND a.clm_create_dt BETWEEN TO_DATE ('01/01/2000', 'dd/mm/yyyy')
                                        AND TO_DATE ('01/01/2010', 'dd/mm/yyyy')

  • Use CASE in HAVING clause

    I feel like this should be simple but it I'm just not grasping it. 
    Say I have this query:
    SELECT order_number, order_date FROM orders
    I basically want to pull any order from the last 24 hours.  Well this is fairly easy for Tue-Fri but when I run the query on Mon, it will have zero results since there are no orders from the weekend.  If the query is ran on Mon it should query
    Fri instead.
    I'm attempting to use case in my having clause but no luck. 
    HAVING (DATEDIFF(dd, GETDATE(), order_date = (CASE order_date WHEN DATENAME(weekday,getdate()) = 'Friday' THEN '3' ELSE '0' END)
    Sure my syntax or parentheses is way off, any help is appreciated.  Thanks.

    Check out the following CASE expression:
    SELECT CASE WHEN datename(dw,getdate()) = 'Monday' THEN
    CONVERT(DATE,(SELECT dateadd(d, -((datepart(weekday, getdate()) + 1 + @@DATEFIRST) % 7), getdate())))
    ELSE CONVERT(DATE, DATEADD(dd, -1, getdate())) END;
    /********* TEST ****************/
    DECLARE @Dt datetime;
    DECLARE @i int = 0; WHILE (@i < 10) BEGIN
    SET @Dt = dateadd(dd, @i, getdate());
    SELECT Today = @Dt, WeekDay=DATENAME(dw,@Dt), PrevBusinessDay= CASE WHEN datename(dw,@Dt) = 'Monday' THEN
    CONVERT(DATE, (SELECT dateadd(d, -((datepart(weekday, @Dt) + 1 + @@DATEFIRST) % 7), @Dt)))
    ELSE CONVERT(DATE, DATEADD(dd, -1, @Dt)) END;
    SET @i += 1; END -- WHILE
    Today WeekDay PrevBusinessDay
    2014-06-20 19:46:45.130 Friday 2014-06-19
    Today WeekDay PrevBusinessDay
    2014-06-23 19:49:04.817 Monday 2014-06-20
    Today WeekDay PrevBusinessDay
    2014-06-24 19:46:45.130 Tuesday 2014-06-23
    Today WeekDay PrevBusinessDay
    2014-06-25 19:46:45.130 Wednesday 2014-06-24
    Today WeekDay PrevBusinessDay
    2014-06-26 19:46:45.130 Thursday 2014-06-25
    Today WeekDay PrevBusinessDay
    2014-06-27 19:46:45.130 Friday 2014-06-26
    Datetime functions:  
    http://www.sqlusa.com/bestpractices/datetimeconversion/
    Consider also implementation with a calendar table.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • 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

  • 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

  • Change my sql query where-clause in an extended controller

    Hello,
    i am trying to change my sql query where-clause in an extended controller
    personAplListVO.setWhereClause(null); // first set to null
    personAplListVO.setWhereClauseParams(null); // first set to null
    personAplListVO.setWhereClause(personAplListVOWhereClause +
    newWhereClause);
    personAplListVO.setWhereClauseParams(whereClauseParams);
    personAplListVO.executeQuery();
    System.out.println(">>>>>>>>getQuery = " + personAplListVO.getQuery());
    when i get the query ( personAplListVO.getQuery()) after executeQuery(), the new newWhereClause values are missing.
    Also i am getting null from personAplListVO.getWhereClause() after executeQuery()
    as if the above code is not making any effect.
    any ideas why?
    Thank you

    Hello,
    My Query:
    /* Formatted on 2011/06/15 15:50 (Formatter Plus v4.8.8) */
    SELECT /*+ FIRST_ROWS */
    NULL AS selectflag, ppf.full_name AS person_name,
    ppf.first_name AS person_first_name, ppf.last_name AS person_last_name,
    ppf.email_address, addr.derived_locale, addr.address_id,
    phn.phone_number, phn.phone_id, ppf.date_of_birth, addr.address_line1,
    (SELECT COUNT (*)
    FROM per_all_assignments_f paf2,
    per_all_people_f ppf2
    WHERE paf2.assignment_type = 'A'
    AND :1 BETWEEN paf2.effective_start_date AND paf2.effective_end_date
    AND paf2.person_id = ppf2.person_id
    AND paf2.effective_start_date BETWEEN ppf2.effective_start_date
    AND ppf2.effective_end_date
    AND ppf2.party_id = ppf.party_id
    HAVING COUNT (*) > 0) AS jobs_applied_for,
    (SELECT MAX (paf.effective_start_date)
    FROM per_all_assignments_f paf,
    per_all_people_f ppf2
    WHERE paf.assignment_type = 'A'
    AND :2 >= paf.effective_start_date
    AND paf.person_id = ppf2.person_id
    AND paf.effective_start_date BETWEEN ppf2.effective_start_date
    AND ppf2.effective_end_date
    AND ppf2.party_id = ppf.party_id) AS last_application,
    ppf.person_id, ppf.effective_start_date, ppf.effective_end_date,
    DECODE (vac.manager_id, :3, 'Y', 'N') AS my_applicants,
    vac.NAME AS vacancy_name, vac.vacancy_id, paf.assignment_id,
    (SELECT /*+ push_subq */
    MIN (pasf.effective_start_date)
    FROM per_all_assignments_f pasf
    WHERE pasf.assignment_id = paf.assignment_id) AS application_date,
    paf.effective_end_date AS assignment_end_date,
    ast.user_status AS application_status, ast.assignment_status_type_id,
    vac.status AS vacancy_status, mgr.full_name AS recruiting_manager,
    mgr.person_id AS recruiting_manager_id,
    mgr.effective_start_date AS effective_start_date1,
    mgr.effective_end_date AS effective_end_date1,
    rec.full_name AS recruiter, rec.person_id AS recruiter_id,
    rec.effective_start_date AS effective_start_date2,
    rec.effective_end_date AS effective_end_date2,
    ppf.per_information_category, ppf.per_information1,
    ppf.per_information2, ppf.per_information3, ppf.per_information4,
    ppf.per_information5, ppf.per_information6, ppf.per_information7,
    ppf.per_information8, ppf.per_information9, ppf.per_information10,
    ppf.per_information11, ppf.per_information12, ppf.per_information13,
    ppf.per_information14, ppf.per_information15, ppf.per_information16,
    ppf.per_information17, ppf.per_information18, ppf.per_information19,
    ppf.per_information20, ppf.per_information21, ppf.per_information22,
    ppf.per_information23, ppf.per_information24, ppf.per_information25,
    ppf.per_information26, ppf.per_information27, ppf.per_information28,
    ppf.per_information29, ppf.per_information30,
    FLOOR
    (irc_location_utility.sdo_miles (iwp.geometry, loc.geometry, 0.01)
    ) AS distance_to_location,
    loc.location_id, loc.derived_locale AS derived_locale1,
    doc.document_id, doc.file_name,
    NVL2 (doc.document_id, 'Y', 'N') AS previewenabled,
    inp.notification_preference_id, ppf.attribute_category, ppf.attribute1,
    ppf.attribute2, ppf.attribute3, ppf.attribute4, ppf.attribute5,
    ppf.attribute6, ppf.attribute7, ppf.attribute8, ppf.attribute9,
    ppf.attribute10, ppf.attribute11, ppf.attribute12, ppf.attribute13,
    ppf.attribute14, ppf.attribute15, ppf.attribute16, ppf.attribute17,
    ppf.attribute18, ppf.attribute19, ppf.attribute20, ppf.attribute21,
    ppf.attribute22, ppf.attribute23, ppf.attribute24, ppf.attribute25,
    ppf.attribute26, ppf.attribute27, ppf.attribute28, ppf.attribute29,
    ppf.attribute30, TO_CHAR (ROWNUM) AS rownumber,
    TO_CHAR
    ((irc_utilities_pkg.get_recruitment_person_id (ppf.person_id, :4))
    ) AS root_person_id,
    TO_CHAR
    (irc_skills_matching_pkg.vacancy_match_percent
    (irc_utilities_pkg.get_recruitment_person_id (ppf.person_id,
    :5
    vac.vacancy_id,
    :6
    ) AS match_percent,
    ppf.party_id, paf.effective_start_date AS assignment_start_date,
    pov.vendor_id, pov.vendor_name, regatmpt.attempt_id AS reg_attempt_id,
    TO_NUMBER (DECODE (regatmpt.raw_score, -1000, NULL, regatmpt.raw_score)
    ) AS reg_attempt_score,
    NVL2
    (regatmpt.mastery_score,
    DECODE (GREATEST (regatmpt.mastery_score, regatmpt.raw_score),
    regatmpt.raw_score, 'P',
    'F'
    NVL2 (fnd_profile.VALUE ('IRC_REGISTER_TEST'),
    NVL2 (inp.attempt_id, 'A', 'N'),
    NULL
    ) AS reg_attempt_status,
    aplatmpt.attempt_id AS apl_attempt_id,
    TO_NUMBER (DECODE (aplatmpt.raw_score, -1000, NULL, aplatmpt.raw_score)
    ) AS apl_attempt_score,
    NVL2
    (aplatmpt.mastery_score,
    DECODE (GREATEST (aplatmpt.mastery_score, aplatmpt.raw_score),
    aplatmpt.raw_score, 'P',
    'F'
    NVL2 (vac.assessment_id, NVL2 (iad.attempt_id, 'A', 'N'), NULL)
    ) AS apl_attempt_status,
    hrl.meaning, hrl.lookup_type, hrl.lookup_code,
    iad.assignment_details_id, iad.considered AS considered,
    vac.business_group_id,
    NVL
    ((SELECT iav.manage_applicants_allowed
    FROM irc_agency_vacancies iav
    WHERE iav.vacancy_id = vac.vacancy_id
    AND iav.agency_id = fnd_profile.VALUE ('IRC_AGENCY_NAME')),
    'Y'
    ) AS manage_applicants_allowed,
    DECODE (paf.source_type, 'ER', 'Y', 'N') AS referred,
    ircreferralinfoeo.start_date, ircreferralinfoeo.end_date,
    (SELECT meaning
    FROM hr_lookups
    WHERE lookup_code = ircreferralinfoeo.source_type
    AND lookup_type = 'REC_TYPE') AS sourcetype,
    DECODE (ircreferralinfoeo.source_type,
    'ER', (SELECT full_name
    FROM per_all_people_f
    WHERE person_id = ircreferralinfoeo.source_person_id
    AND SYSDATE BETWEEN effective_start_date
    AND effective_end_date),
    ircreferralinfoeo.source_name
    ) AS sourcename,
    ircreferralinfoeo.object_id, ircreferralinfoeo.object_type
    FROM per_addresses addr,
    per_phones phn,
    per_all_people_f ppf,
    per_all_assignments_f paf,
    per_all_vacancies vac,
    per_assignment_status_types_v ast,
    per_all_people_f mgr,
    per_all_people_f rec,
    irc_notification_preferences inp,
    hr_locations_all_vl loc,
    irc_documents doc,
    irc_search_criteria iwp,
    per_all_people_f irc_ppf,
    po_vendors pov,
    ota_attempts regatmpt,
    irc_assignment_details_f iad,
    ota_attempts aplatmpt,
    hr_lookups hrl,
    irc_referral_info ircreferralinfoeo
    WHERE irc_utilities_pkg.get_recruitment_person_id (ppf.person_id, :7) =
    irc_ppf.person_id
    AND :8 BETWEEN ppf.effective_start_date AND ppf.effective_end_date
    AND irc_ppf.party_id = ppf.party_id
    AND ppf.person_id = paf.person_id
    AND paf.assignment_type = 'A'
    AND paf.vacancy_id = vac.vacancy_id
    AND :9 BETWEEN paf.effective_start_date AND paf.effective_end_date
    AND paf.assignment_status_type_id = ast.assignment_status_type_id
    AND irc_ppf.person_id = doc.person_id(+)
    AND irc_ppf.person_id = phn.parent_id(+)
    AND phn.parent_table(+) = 'PER_ALL_PEOPLE_F'
    AND phn.phone_type(+) = 'H1'
    AND :10 BETWEEN NVL (phn.date_from(+), :11) AND NVL (phn.date_to(+), :12)
    AND vac.manager_id = mgr.person_id(+)
    AND :13 BETWEEN mgr.effective_start_date(+) AND mgr.effective_end_date(+)
    AND vac.recruiter_id = rec.person_id(+)
    AND :14 BETWEEN rec.effective_start_date(+) AND rec.effective_end_date(+)
    AND irc_ppf.person_id = inp.person_id(+)
    AND inp.person_id = addr.person_id(+)
    AND NVL (inp.address_id, DECODE (addr.address_type(+), 'REC', addr.address_id(+),
    -1)) = addr.address_id(+)
    AND :15 BETWEEN addr.date_from(+) AND NVL (addr.date_to(+), :16)
    AND loc.location_id(+) = vac.location_id
    AND doc.TYPE(+) LIKE '%RESUME'
    AND doc.end_date(+) IS NULL
    AND irc_ppf.person_id = iwp.object_id(+)
    AND iwp.object_type(+) = 'WPREF'
    AND :17 BETWEEN irc_ppf.effective_start_date AND irc_ppf.effective_end_date
    AND ( inp.agency_id = fnd_profile.VALUE ('IRC_AGENCY_NAME')
    OR fnd_profile.VALUE ('IRC_AGENCY_NAME') IS NULL
    AND inp.agency_id = pov.vendor_id(+)
    AND inp.attempt_id = regatmpt.attempt_id(+)
    AND paf.assignment_id = iad.assignment_id(+)
    AND :18 BETWEEN iad.effective_start_date(+) AND iad.effective_end_date(+)
    AND iad.latest_details(+) = 'Y'
    AND iad.attempt_id = aplatmpt.attempt_id(+)
    AND hrl.lookup_type(+) = 'VACANCY_STATUS'
    AND vac.status = hrl.lookup_code(+)
    AND paf.assignment_id = ircreferralinfoeo.object_id(+)
    AND SYSDATE BETWEEN ircreferralinfoeo.start_date(+) AND ircreferralinfoeo.end_date(+)
    AND ( 1 = 1
    AND (NVL (doc.document_id, 1) =
    NVL ((SELECT MAX (idoc1.document_id)
    FROM irc_documents idoc1
    WHERE idoc1.person_id = irc_ppf.person_id
    AND idoc1.TYPE IN ('RESUME', 'AUTO_RESUME')
    AND idoc1.end_date IS NULL
    AND idoc1.last_update_date =
    (SELECT MAX (idoc2.last_update_date)
    FROM irc_documents idoc2
    WHERE idoc2.person_id = irc_ppf.person_id
    AND idoc2.TYPE IN
    ('RESUME', 'AUTO_RESUME')
    AND idoc2.end_date IS NULL)),
    1
    and my where clause that i want to append to the existing one:
    and ppf.sex = 'M' and ppf.nationality = '1680'
    my processFormRequest function in my extended CO
    public void processFormRequest(OAPageContext pageContext,
    OAWebBean webBean) {
    super.processFormRequest(pageContext, webBean);
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    String genderValue = pageContext.getParameter("gender");
    String nationality = pageContext.getParameter("nationality");
    ViewObject personAplListVO = am.findViewObject("PersonAplListVO");
    String personAplListVOWhereClause = personAplListVO.getWhereClause();
    Object[] whereClauseParams = personAplListVO.getWhereClauseParams();
    String newWhereClause = "";
    //gender
    if (genderValue != null && !genderValue.trim().equals("")) {
    newWhereClause += " and ppf.sex = '" + genderValue + "'";
    //nationality
    if (nationality != null && !nationality.trim().equals("")) {
    newWhereClause += " and ppf.nationality = '" + nationality + "'";
    System.out.println("\n>>>>>>>>getQuery = " + personAplListVO.getQuery());
    System.out.println("\n>>>>>>>>newWhereClause = " + newWhereClause);
    if (!newWhereClause.equals("")) {
    personAplListVO.clearCache();
    personAplListVO.setWhereClause(null); // first set to null
    personAplListVO.setWhereClauseParams(null); // first set to null
    personAplListVO.setWhereClause(personAplListVOWhereClause +
    newWhereClause);
    personAplListVO.setWhereClauseParams(whereClauseParams);
    personAplListVO.executeQuery();
    // System.out.println(">>>>>>>>newWhereClause" +
    // personAplListVOWhereClause + newWhereClause);
    // System.out.println(">>>>>>>>getWhereClause" +
    // personAplListVO.getWhereClause());
    // System.out.println(">>>>>>>>getQuery = " +
    // personAplListVO.getQuery());
    any tips?
    thanks a lot

  • 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

  • Having Clause In Discoverer

    Hi All,
    Current I am working on a Discoverer report modification,
    Curent report query i ahve taken from View-Sql Inspector that is mentioned below(Sample).
    Here i wanted to change the Having condition of the below query through the discoverer tool.
    Can any one help me in this regard?
    SELECT (bolinf.xxbt_disco_common_pkg.get_sitelevel_coll (o222236.customer_number)) AS c_18
    , o222241.segment1 || '-' || o222241.segment2 || '-' || o222241.segment3 || '-' || o222241.segment4 || '-' || o222241.segment5 || '-' || o222241.segment6 || '-' || o222241.segment7 || '-'
    || o222241.segment8 || '-' || o222241.segment9 || '-' || o222241.segment10 AS c_19
    ,bolinf.xxbt_disco_common_pkg.get_rev_lob (o222245.gl_id_rev) AS c_22
    , (bolinf.xxbt_disco_common_pkg.get_siebel_account_code (o222245.gl_id_rev)) AS c_3
    , (bolinf.xxbt_disco_common_pkg.get_siebel_account_name (o222245.gl_id_rev)) AS c_4
    ,o222246.city AS e222753
    ,o222236.customer_category_code AS e222864
    ,o222236.customer_class_code AS e222869
    ,o222236.customer_name AS e222881
    ,o222236.customer_number AS e222885
    ,o222239.due_date AS e222988
    ,o222245.fob_point AS e223035
    ,o222239.invoice_currency_code AS e223477
    ,o222236.profile_class_name AS e223794
    ,o222239.staged_dunning_level AS e224084
    ,o222239.trx_date AS e224181
    ,o222239.trx_number AS e224185
    ,SUM (CASE
    FROM ar.ar_collectors o222235
    ,apps.ar_customers_v o222236
    ,apps.ar_payment_schedules o222239
    ,gl.gl_code_combinations o222241
    ,ar.hz_cust_acct_sites_all o222243
    ,ar.hz_cust_site_uses_all o222245
    ,ar.hz_locations o222246
    ,ar.hz_party_sites o222247
    ,ar.ra_cust_trx_line_gl_dist_all o222251
    , (SELECT lv.lookup_type
    ,lv.lookup_code
    ,lv.meaning
    ,lv.enabled_flag
    ,lv.start_date_active
    ,lv.end_date_active
    FROM fnd_lookup_values lv
    WHERE lv.LANGUAGE = USERENV ('LANG')
    AND lv.view_application_id = 222
    AND lv.security_group_id = 0
    AND lv.lookup_type = 'INV/CM') o410858
    ,ar.hz_customer_profiles o415961
    , (SELECT crm.customer_id
    ,crm.primary_flag
    ,crm.site_use_id
    ,rm.NAME "Payment Method Name"
    ,haou.NAME
    ,l_cat.meaning "Account Manager"
    FROM ra_cust_receipt_methods crm
    ,ar_receipt_methods rm
    ,hz_cust_site_uses_all hcs
    ,hz_cust_acct_sites_all hcasa
    ,hr_all_organization_units haou
    ,ar_lookups l_cat
    WHERE crm.receipt_method_id = rm.receipt_method_id(+)
    AND hcs.site_use_id = crm.site_use_id
    AND haou.organization_id = hcs.org_id
    AND hcasa.cust_account_id = crm.customer_id
    AND hcasa.cust_acct_site_id(+) = hcs.cust_acct_site_id
    AND hcasa.customer_category_code = l_cat.lookup_code(+)
    AND l_cat.lookup_type(+) = 'ADDRESS_CATEGORY'
    AND haou.NAME NOT LIKE '%OLD%') o681593
    WHERE ( (o222236.customer_id = o222239.customer_id)
    AND (o222241.code_combination_id = o222251.code_combination_id)
    AND (o222243.cust_acct_site_id(+) = o222245.cust_acct_site_id)
    AND (o222245.site_use_id(+) = o222239.customer_site_use_id)
    AND (o222246.location_id(+) = o222247.location_id)
    AND (o222247.party_site_id(+) = o222243.party_site_id)
    AND (o222251.customer_trx_id(+) = o222239.customer_trx_id)
    AND (o410858.lookup_code = o222239.CLASS)
    AND (o222235.collector_id = o415961.collector_id)
    AND (o415961.cust_account_id = o222236.customer_id)
    AND (o681593.site_use_id = o222245.site_use_id)
    AND (o415961.site_use_id IS NULL)
    AND (o222251.account_set_flag(+) = 'N')
    AND o222239.trx_number ='29801276'
    --AND (o222235.NAME = :"Collector Name")
    --AND (o222236.profile_class_name = :"Profile Class Name")
    --AND (( o222236.customer_category_code = :"Customer Category"
    -- OR :"Customer Category" IS NULL))
    --AND (( o222236.customer_class_code = :"Customer Class"
    -- OR :"Customer Class" IS NULL))
    --AND (o222239.invoice_currency_code = :"Currency")
    AND ((DECODE ('Y', 'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0), NVL (o222239.amount_due_remaining, 0))) 0)
    AND (o222251.account_class(+) = 'REC')
    GROUP BY (bolinf.xxbt_disco_common_pkg.get_sitelevel_coll (o222236.customer_number))
    , o222241.segment1 || '-' || o222241.segment2 || '-' || o222241.segment3 || '-' || o222241.segment4 || '-' || o222241.segment5 || '-' || o222241.segment6 || '-' || o222241.segment7 || '-'
    || o222241.segment8 || '-' || o222241.segment9 || '-' || o222241.segment10
    ,bolinf.xxbt_disco_common_pkg.get_rev_lob (o222245.gl_id_rev)
    , (bolinf.xxbt_disco_common_pkg.get_siebel_account_code (o222245.gl_id_rev))
    , (bolinf.xxbt_disco_common_pkg.get_siebel_account_name (o222245.gl_id_rev))
    ,o222246.city
    ,o222236.customer_category_code
    ,o222236.customer_class_code
    ,o222236.customer_name
    ,o222236.customer_number
    ,o222239.due_date
    ,o222245.fob_point
    ,o222239.invoice_currency_code
    ,o222236.profile_class_name
    ,o222239.staged_dunning_level
    ,o222239.trx_date
    ,o222239.trx_number
    ,o410858.meaning
    ,o681593.primary_flag
    ,o681593."Payment Method Name"
    ,o681593."Account Manager"
    HAVING ((((SUM (CASE
    WHEN (TO_DATE ('30-APR-2011', 'DD-MON-YYYY') - o222239.due_date) BETWEEN 1 AND 30 THEN (DECODE ('Y'
    ,'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0)
    ,NVL (o222239.amount_due_remaining, 0)
    ELSE 0
    END)
    + (SUM (CASE
    WHEN (TO_DATE ('30-APR-2011', 'DD-MON-YYYY') - o222239.due_date) BETWEEN 31 AND 60 THEN (DECODE ('Y'
    ,'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0)
    ,NVL (o222239.amount_due_remaining, 0)
    ELSE 0
    END)
    + (SUM (CASE
    WHEN (TO_DATE ('30-APR-2011', 'DD-MON-YYYY') - o222239.due_date) BETWEEN 61 AND 90 THEN (DECODE ('Y'
    ,'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0)
    ,NVL (o222239.amount_due_remaining, 0)
    ELSE 0
    END)
    + (SUM (CASE
    WHEN (TO_DATE ('30-APR-2011', 'DD-MON-YYYY') - o222239.due_date) BETWEEN 91 AND 120 THEN (DECODE ('Y'
    ,'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0)
    ,NVL (o222239.amount_due_remaining, 0)
    ELSE 0
    END)
    + (SUM (CASE
    WHEN (TO_DATE ('30-APR-2011', 'DD-MON-YYYY') - o222239.due_date) BETWEEN 121 AND 150 THEN (DECODE ('Y'
    ,'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0)
    ,NVL (o222239.amount_due_remaining, 0)
    ELSE 0
    END)
    + (SUM (CASE
    WHEN (TO_DATE ('30-APR-2011', 'DD-MON-YYYY') - o222239.due_date) BETWEEN 151 AND 180 THEN (DECODE ('Y'
    ,'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0)
    ,NVL (o222239.amount_due_remaining, 0)
    ELSE 0
    END)
    + (SUM (CASE
    WHEN (TO_DATE ('30-APR-2011', 'DD-MON-YYYY') - o222239.due_date) BETWEEN 181 AND 365 THEN (DECODE ('Y'
    ,'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0)
    ,NVL (o222239.amount_due_remaining, 0)
    ELSE 0
    END)
    + (SUM (CASE
    WHEN (TO_DATE ('30-APR-2011', 'DD-MON-YYYY') - o222239.due_date) < 1 THEN (DECODE ('Y'
    ,'Y', NVL (o222239.amount_due_remaining * NVL (o222239.exchange_rate, 1), 0)
    ,NVL (o222239.amount_due_remaining, 0)
    ELSE 0
    END)
    ) <> 0
    ORDER BY e222881 ASC;

    Duplicate post -- Having Clause In Discoverer

Maybe you are looking for