Case Statement in a Where clause help

Oracle Database 11g Release 11.2.0.1.0 - 64bit Production
PL/SQL Release 11.2.0.1.0 - Production
"CORE     11.2.0.1.0     Production"
TNS for Linux: Version 11.2.0.1.0 - Production
NLSRTL Version 11.2.0.1.0 - Production
Hello,
I have an APEX application that I need to build a SQL statement for a LOV (List of Values). I have a hidden filed that contains the customer type which can be an 'R' or 'B'. The query needs to be able to display two different result sets based on the customer type of 'R' or 'B'.
If the customer type is 'R' then:
SELECT drg_descr d, drg_code r
FROM distance_ranges
WHERE  drg_min_miles IN (0,5)
ORDER BY drg_min_milesIf the customer type is 'B' then:
SELECT drg_descr d, drg_code r
FROM distance_ranges
WHERE  drg_min_miles IN (0,5,10,15,20)
ORDER BY drg_min_milesCan someone help me with what I think needs to be a case statement?
Thanks,
Joe

Hi,
You can try CASE statement with WHERE clause
SELECT drg_descr d, drg_code r
FROM distance_ranges
WHERE (CASE param_cust_type
WHEN(param_cust_type='R') THEN (drg_min_miles IN (0, 5)
WHEN (param_cust_type='B') THEN (drg_min_miles IN (0,5,10,15,20)
END;
Please try and let me know if anything wrong.
Anyone from the forum comment my code if there is any wrong.
Thanks!
Naresh

Similar Messages

  • Query Tuning - using CASE statement in the WHERE clause

    Hi All,
    My query has been modified to use a CASE statement in the WHERE clause to consider data from certain columns based on a parameter value. This modified query is doing a full table scan and running endlessly. Please suggest what may be done to improve its performance:
    Query:
    SELECT LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))) AS summary_date,
    os.acctnum,
    os.avieworigin_refid,
    COUNT(1) cnt_articleview,
    SUM(NVL(autocompletedterm,0)) cnt_autocompletedterm
    FROM TABLE1 os
    WHERE os.acctnum IS NOT NULL
    AND os.avieworigin_refid IS NOT NULL
    AND os.requestdatetime IS NOT NULL
    AND UPPER(os.success_ind) = 'S'
    AND CASE WHEN
    Param_ValueToCheck  = 'FULL' AND get_date_timestamp(os.requestdatetime)  BETWEEN
    TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND
    TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    THEN 1
    WHEN
    Param_ValueToCheck  = 'INCR' AND os.entry_createddate  BETWEEN
    TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND
    TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    THEN 1
    END = 1
    AND CASE WHEN
    Param_ValueToCheck  = 'FULL' AND os.entry_CreatedDate BETWEEN
    TO_DATE('01-APR-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') AND
    TO_DATE('07-JUN-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    THEN 1
    WHEN
    Param_ValueToCheck  = 'INCR' THEN 1
    END = 1
    GROUP BY LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))), os.acctnum,os.avieworigin_refid;Table Description:
    (Number of rows : approx > 600,000,000)
    Name                           Null     Type      
    ARTICLEID                      NOT NULL NUMBER(20)
    USERKEY                                 NUMBER(10)
    AVIEWORIGIN_REFID                       VARCHAR2(10)
    SUCCESS_IND                             VARCHAR2(2)
    ENTRY_CREATEDDATE                       DATE      
    CREATED_BY                              VARCHAR2(10)
    FILENUMBER                              NUMBER(10)
    LINENUMBER                              NUMBER(10)
    ACCTNUM                                 VARCHAR2(10)
    AUTOCOMPLETEDTERM                       NUMBER(2) 
    REQUESTDATETIME                         VARCHAR2(19)Explain Plan
    SQL> select * from table(dbms_xplan.display);
    PLAN_TABLE_OUTPUT
    Plan hash value: 2224314832
    | Id  | Operation            | Name              | Rows  | Bytes | Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT     |                   |   590 | 33040 |  2501K  (1)| 08:20:15 |       |       |
    |   1 |  HASH GROUP BY       |                   |   590 | 33040 |  2501K  (1)| 08:20:15 |       |       |
    |   2 |   PARTITION RANGE ALL|                   |   590 | 33040 |  2501K  (1)| 08:20:15 |     1 |1048575|
    |*  3 |    TABLE ACCESS FULL | TABLE1 |   590 | 33040 |  2501K  (1)| 08:20:15 |     1 |1048575|
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       3 - filter(UPPER("OS"."SUCCESS_IND")='S' AND CASE  WHEN ('FULL'='FULL' AND
                  "OS"."ENTRY_CREATEDDATE">=TO_DATE(' 2011-04-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND
                  "OS"."ENTRY_CREATEDDATE"<=TO_DATE(' 2011-06-07 00:00:00', 'syyyy-mm-dd hh24:mi:ss')) THEN 1 WHEN
                  'FULL'='INCR' THEN 1 END =1 AND "OS"."REQUESTDATETIME" IS NOT NULL AND CASE  WHEN ('FULL'='FULL'
                  AND "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")>=TO_DATE(' 2011-05-01 00:00:00', 'syyyy-mm-dd
                  hh24:mi:ss') AND "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")<=TO_DATE(' 2011-05-31 00:00:00',
                  'syyyy-mm-dd hh24:mi:ss')) THEN 1 WHEN ('FULL'='INCR' AND "OS"."ENTRY_CREATEDDATE">=TO_DATE('
                  2011-05-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND "OS"."ENTRY_CREATEDDATE"<=TO_DATE('
    PLAN_TABLE_OUTPUT
                  2011-05-31 00:00:00', 'syyyy-mm-dd hh24:mi:ss')) THEN 1 END =1 AND "OS"."ACCTNUM" IS NOT NULL AND
                  "OS"."AVIEWORIGIN_REFID" IS NOT NULL)Edited by: Chaitanya on Jun 9, 2011 2:44 AM
    Edited by: Chaitanya on Jun 9, 2011 2:47 AM

    Hi Dom,
    Modified Query:
    SELECT LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))) AS summary_date,
    os.acctnum,
    os.avieworigin_refid,
    COUNT(1) cnt_articleview,
    SUM(NVL(autocompletedterm,0)) cnt_autocompletedterm
    FROM TABLE1 os
    WHERE os.acctnum IS NOT NULL
    AND os.avieworigin_refid IS NOT NULL
    AND os.requestdatetime IS NOT NULL
    AND UPPER(os.success_ind) = 'S'
    AND (('FULL'  = 'FULL'
    AND  (get_date_timestamp(os.requestdatetime)  BETWEEN TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
                   AND TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    AND   os.entry_CreatedDate BETWEEN TO_DATE('01-APR-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
                   AND TO_DATE('07-JUN-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
    OR ('FULL'  = 'INCR'
    AND os.entry_createddate  BETWEEN TO_DATE('01-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS')
                   AND TO_DATE('31-MAY-2011 00:00:00','DD-MON-YYYY HH24:MI:SS') ))
    GROUP BY LAST_DAY(TRUNC(TO_TIMESTAMP(os.requestdatetime, 'yyyymmddhh24:mi:ss.ff4'))), os.acctnum,os.avieworigin_refid;Execute Plan:
    PLAN_TABLE_OUTPUT
    Plan hash value: 3615447714
    | Id  | Operation                 | Name              | Rows  | Bytes |TempSpc| Cost (%CPU)| Time     | Pstart| Pstop |
    |   0 | SELECT STATEMENT          |                   | 25125 |  1374K|       |   407K  (1)| 01:21:36 |       |       |
    |   1 |  HASH GROUP BY            |                   | 25125 |  1374K|  3768K|   407K  (1)| 01:21:36 |       |       |
    |   2 |   PARTITION RANGE ITERATOR|                   | 25125 |  1374K|       |   407K  (1)| 01:21:32 |    29 |    31 |
    |*  3 |    TABLE ACCESS FULL      | TABLE1 | 25125 |  1374K|       |   407K  (1)| 01:21:32 |    29 |    31 |
    PLAN_TABLE_OUTPUT
    Predicate Information (identified by operation id):
       3 - filter("OS"."ENTRY_CREATEDDATE">=TO_DATE(' 2011-04-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND
                  UPPER("OS"."SUCCESS_IND")='S' AND "OS"."REQUESTDATETIME" IS NOT NULL AND
                  "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")>=TO_DATE(' 2011-05-01 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND
                  "ODS"."GET_DATE_TIMESTAMP"("REQUESTDATETIME")<=TO_DATE(' 2011-05-31 00:00:00', 'syyyy-mm-dd hh24:mi:ss') AND
                  "OS"."ACCTNUM" IS NOT NULL AND "OS"."AVIEWORIGIN_REFID" IS NOT NULL AND "OS"."ENTRY_CREATEDDATE"<=TO_DATE('
                  2011-06-07 00:00:00', 'syyyy-mm-dd hh24:mi:ss'))Edited by: Chaitanya on Jun 9, 2011 4:51 AM

  • Query Tuning - using CASE statement in the WHERE clause - Duplicate Post

    Duplicate Post by mistake.
    Please check
    Query Tuning - using CASE statement in the WHERE clause
    Edited by: Chaitanya on Jun 9, 2011 2:45 AM
    Edited by: Chaitanya on Jun 9, 2011 2:46 AM

    Duplicate Post by mistake.
    Please check
    Query Tuning - using CASE statement in the WHERE clause
    Edited by: Chaitanya on Jun 9, 2011 2:45 AM
    Edited by: Chaitanya on Jun 9, 2011 2:46 AM

  • How do I use the CASE statement  in the where clause?

    Hello Everyone,
    I have 2 queries that do what I need to do but I am trying to learn how to use the CASE statement.
    I have tried to combine these 2 into one query using a case statement but don't get the results I need.
    Could use some help on how to use the case syntax to get the results needed.
    thanks a lot
    select segment_name,
    product_type,
    count (distinct account_id)
    FROM NL_ACCT
    where
    ind = 'N'
    and
    EM_ind = 'N'
    and product_type in ('TAX','PAY')
    and acct_open_dt between (cast('2006-01-17' as date)) and (cast('2006-01-17' as date) + 60)
    GROUP BY 1,2
    order by product_type
    select segment_name,
    product_type,
    count (distinct account_id)
    FROM NL_ACCT
    where
    ind = 'N'
    and
    EM_ind = 'N'
    and product_type not in ('TAX','PAY')
    and acct_open_dt between (cast('2006-01-17' as date)) and (cast('2006-01-17' as date) + 30)
    group by 1,2
    order by product_type

    Something like:
    SELECT segment_name, product_type,
           SUM(CASE WHEN account_id IN ('TAX','PAY') and
                         acct_open_dt BETWEEN TO_DATE('2006-01-17', 'yyyy-mm-dd') and
                               TO_DATE('2006-01-17', 'yyyy-mm-dd') + 60 THEN 1
                    ELSE 0 END) tax_pay,
           SUM(CASE WHEN account_id NOT IN ('TAX','PAY') and
                         acct_open_dt BETWEEN TO_DATE('2006-01-17', 'yyyy-mm-dd') and
                               TO_DATE('2006-01-17', 'yyyy-mm-dd') + 30 THEN 1
                    ELSE 0 END) not_tax_pay
    FROM NL_ACCT
    WHERE ind = 'N' and
          em_ind = 'N' and
          acct_open_dt BETWEEN TO_DATE('2006-01-17', 'yyyy-mm-dd') and
                               TO_DATE('2006-01-17', 'yyyy-mm-dd') + 60
    GROUP BY segment_name, product_type
    ORDER BY product_typeNote: You cannor GROUP BY 1,2, you need to explicitly name the columns to group by.
    HTH
    John

  • Case stament use in where clause  grive error

    i want to use this conditions but gives error. Please give me the solution of it
    WHERE
    CASE
    WHEN CANCELLED_DATE IS NULL THEN
    TO_DATE(INV_GL_DATE,'DD-MON-YY') <= TO_DATE (:P_DATE1,'DD-MON-YY')
    ELSE
    TO_DATE(INV_GL_DATE,'DD-MON-YY') >= TO_DATE(:P_DATE1,'DD-MON-YY')
    END) --- <= TO_DATE(:P_DATE1,'DD-MON-YY')

    Hi,
    Remember that a CASE expression always evaluates to a single value in one of the SQL datatypes, such as VARCHAR2, NUMBER or DATE. (There is no Boolean datatype in SQL.)
    You can't say
    WHERE   CASE ... END;for the same reason that you can't say
    WHERE   'Hello, world!';orWHERE   100;or
    WHERE   SYSDATE;CASE expressions are really valuable because they allow you do perform IF-THEN-ELSE logic in places where you normally can't, like the SELECT clause.
    The WHERE clause is a place where you can perform IF-THEN-ELSE logic anyway, so there's rarely a need for a CASE expression in a WHERE clause. It's just as efficient and just as clear (if not more so) to put all your conditions directly in the WHERE clause, like Max demonstrated.
    Edited by: Frank Kulash on Feb 26, 2010 10:13 AM
    user11995078 wrote:
    Thanks Dear But how can we use with case and decodeWhy do you want to?
    CASE does not help in this problem, any more than regular expressions or CONNECT BY or MODEL help. They are all great tools for particular jobs, but not for this job. Asking "How can I use CASE to do this?" Is like asking "How can I use a hammer to tighten a bolt?" Perhaps there is a way, but it's likely to be contrived and ridiculous.
    Here's the least ridiculous way I can think of:
    WHERE     ( TO_DATE (INV_GL_DATE, 'DD-MON-YY') 
         - TO_DATE (:P_DATE1,     'DD-MON-YY')
         ) * CASE
                 WHEN  cancelled_date  IS NULL  THEN  1
                    `                            ELSE -1
             END <= 0

  • Case statement in order by clause

    Hi,
    I have written the below query which is having CASE statement in ORDER BY clause. Please let me know what mistake i have done in the query because am getting "Missing Keyword" Error.
    SELECT opn_quest_id, seq_nbr
    FROM opinion_question
    order by case when :p=1 then
    opn_quest_id,seq_nbr
    else
    opn_quest_id
    end;
    Thanks,
    Santhosh.S

    Try Ignore the following solution.
    SELECT   opn_quest_id, seq_nbr
    FROM   opinion_question
    ORDER BY   CASE
    WHEN : p = 1 THEN opn_quest_id || seq_nbr
    ELSE opn_quest_id
    END;
    What are the data type of the corresponding columns used in the CASE Statement? I have assumed it to be strings.
    !http://www.mysmiley.net/imgs/smile/sad/sad0049.gif! My Apologies....
    Regards,
    Jo
    Edited by: Joice John on Jul 13, 2009 3:07 AM
    Wrong Solution. Corrected by Sven.

  • CASE Statement error in function -- Please help!

    Hi All,
    I created a function in my report.
    It has a SQL query similar to the one below. The query works fine in SQL plus.
    It has a CASE statement. I am getting error at line4 at the select statement. Error is: "Encountered symbol 'SELECT'....."
    Can we use CASE statements like this in reports that use SELECT statements for RETURN EXPRESSIONS. Do we have to do any special?
    Can someone help me out of this trouble?
    THanks in advance.
    SELECT PARENT_id,
         CASE WHEN EXISTS (SELECT PARENT_id FROM CHILD CH1 WHERE CH1.PARENT_id = PARENT.PARENT_id AND UPPER(CH1.description) LIKE '%ABC%') THEN
              (SELECT CH2.MOD_id FROM CHILD CH2 WHERE CH2.PARENT_id = PARENT.PARENT_id AND UPPER(CH2.description) LIKE '%ABC%')
         ELSE
              (SELECT MOD_id FROM
              (SELECT MOD_id,PARENT_id FROM CHILD CH3 ORDER BY started) MOD2 WHERE MOD2.PARENT_id = PARENT.PARENT_id AND ROWNUM = 1
         END
    ) MOD_ID
    FROM PARENT;

    take out the parentheses after the PARENT_ID and see
    like below
    SELECT parent_id,
           CASE
              WHEN EXISTS (
                     SELECT parent_id
                       FROM CHILD ch1
                      WHERE ch1.parent_id = PARENT.parent_id
                        AND UPPER (ch1.description) LIKE '%ABC%')
                 THEN (SELECT ch2.mod_id
                         FROM CHILD ch2
                        WHERE ch2.parent_id = PARENT.parent_id
                          AND UPPER (ch2.description) LIKE '%ABC%')
              ELSE (SELECT mod_id
                      FROM (SELECT   mod_id, parent_id
                                FROM CHILD ch3
                            ORDER BY started) mod2
                     WHERE mod2.parent_id = PARENT.parent_id AND ROWNUM = 1)
           END AS mod_id
      FROM PARENT;       

  • Case Statement ....please help :)

    Hi Guys\Gals,
    Just wondering if anyone can tell me the correct usage of the case statement:)
    I want to select counts for particular date ranges to come out as seperate columns.
    Is the Sql Server Case appliable in oracle circumstances?
    This is what im doing:
    select count(case when to_char(logtime,'MM') = '01' then source else 0 end) as January
    from messagetransactionlog
    SQL Error: ORA-00932: inconsistent datatypes: expected CHAR got NUMBER
    Then im getting something like from keyword not found!!
    Plz help :)
    Thanks
    Robert

    Hopefully im not boring people now :)
    can the case statement, as follows:
    count(case when logtime = '07-07' then UNIQUES else null end) as Jul
    be changed to only count distinct rows?
    count distinct (case when logtime = '07-07' then UNIQUES else null end) as Jul
    #SQL Error: ORA-00923: FROM keyword not found where expected
    count (case when logtime = '07-07' then distinct UNIQUES else null end) as Jul
    #SQL Error: ORA-00923: FROM keyword not found where expected

  • Where clause help.

    Hi,
    I have table with a partition on a column of date data type. Each partition has a month's data in it. I use the following query to fetch the data:
    select column1, column2
    from table1 partition(apr2011)
    where trunc(date_column) = '01-APR-11';
    The query works fast when partition has less records(data for 10-15 days). But as the number of records in the partition increases(at month end), the time taken to retrieve the result is much more. Request you to please help me with an alternative for the 'where clause' to get faster data.
    Thanks.

    Thanks Mohamed,
    Finally the coin dropped
    SQL> CREATE TABLE sales_range
    (salesman_id  NUMBER(5),
    sales_date    DATE)
    PARTITION BY RANGE(sales_date)
    PARTITION sales_jan2000 VALUES LESS THAN(TO_DATE('02/01/2000','MM/DD/YYYY')),
    PARTITION sales_feb2000 VALUES LESS THAN(TO_DATE('03/01/2000','MM/DD/YYYY')),
    PARTITION sales_mar2000 VALUES LESS THAN(TO_DATE('04/01/2000','MM/DD/YYYY')),
    PARTITION sales_apr2000 VALUES LESS THAN(TO_DATE('05/01/2000','MM/DD/YYYY'))
    Table created.
    SQL> set autotrace traceonly explain
    SQL> SELECT * FROM   sales_range
    WHERE  sales_date = TO_DATE ( '03/01/2000', 'MM/DD/YYYY');
    no rows selected.
    Execution Plan
       0       SELECT STATEMENT Optimizer Mode=ALL_ROWS (Cost=2 Card=1 Bytes=97)
       1    0    PARTITION RANGE SINGLE (Cost=2 Card=1 Bytes=97)
       2    1      TABLE ACCESS FULL KORT.SALES_RANGE (Cost=2 Card=1 Bytes=97)
    SQL> SELECT * FROM   sales_range
    WHERE  TRUNC (sales_date) = TO_DATE ( '03/01/2000', 'MM/DD/YYYY');
    no rows selected.
    Execution Plan
       0       SELECT STATEMENT Optimizer Mode=ALL_ROWS (Cost=2 Card=1 Bytes=97)
       1    0    PARTITION RANGE ALL (Cost=2 Card=1 Bytes=97)
       2    1      TABLE ACCESS FULL KORT.SALES_RANGE (Cost=2 Card=1 Bytes=97)
    Your explanation If using TRUNC, you don't get partition elimination
    Regards
    Peter

  • Case statement with group by clause

    SELECT STP, CASE WHEN Alternate IS NULL THEN 3 ELSE 4 END as Ind,
    CASE WHEN Alternate IS NULL THEN 'New Address' ELSE 'New Location' END as Description , Count(*) Rec_Cnt
    FROM t_Ids
    group by STP, CASE WHEN Alternate IS NULL THEN 3 ELSE 4 END, CASE WHEN Alternate IS NULL THEN 'New Address' ELSE 'New Location'
    ORDER BY 1,2,3
    I need a query something like this. Does anyone has any idea on this???

    You're missing the END on the GROUP BY Case statement, but otherwise this looks fine.
    What problem are you having?
    Also, please post DDL
    Thanks
    Carl

  • Combining Sum/Case queries with different where clauses into one query

    Hello,
    I'm trying to combine 2 queries that contain the SUM/CASE function into one query that'll produce the output in the same table, rather than having two The thing is, the two queries have different conditions. I've created a sample data table and outputs to better describe what I'm trying to achieve.
    SAMPLE_DATA
    DEPT
    PROD_CODE
    FLAG1
    FLAG2
    HO
    A
    NULL
    Y
    HO
    B
    NULL
    Y
    HO
    A
    Y
    NULL
    HO
    B
    Y
    Y
    IT
    A
    NULL
    Y
    IT
    C
    NULL
    NULL
    ENG
    B
    NULL
    Y
    ENG
    C
    NULL
    Y
    ENG
    C
    Y
    Y
    MKT
    A
    Y
    Y
    The first query I'm running is to sum the product codes department wise while checking if FLAG1 is Y. The second query is checking if FLAG2 is Y.
    First Query:
    select DEPT, sum(case PRODUCT_CODE when 'A' then 1 else 0 end),
    sum(case PRODUCT_CODE when 'B' then 1 else 0 end),
    sum(case PRODUCT_CODE when 'C' then 1 else 0 end)
    from SAMPLE_DATA where FLAG1 is not null group by DEPT;
    Second Query:
    select DEPT, sum(case PRODUCT_CODE when 'A' then 1 else 0 end),
    sum(case PRODUCT_CODE when 'B' then 1 else 0 end),
    sum(case PRODUCT_CODE when 'C' then 1 else 0 end)
    from SAMPLE_DATA where FLAG2 is not null group by DEPT;
    FIRST QUERY OUTPUT:
    DEPT
    PRODA_FL1
    PRODB_FL1
    PRODC_FL1
    HO
    1
    1
    0
    IT
    0
    0
    0
    ENG
    0
    0
    1
    MKT
    1
    0
    0
    SECOND QUERY OUTPUT:
    DEPT
    PRODA_FL2
    PRODB_FL2
    PRODC_FL2
    HO
    1
    2
    0
    IT
    1
    0
    0
    ENG
    0
    1
    2
    MKT
    1
    0
    0
    My aim is to combine both the queries so that the output is displayed the same way as the table below.
    DESIRED OUTPUT:
    DEPT
    PRODA_FL1
    PRODB_FL1
    PRODC_FL1
    PRODA_FL2
    PRODB_FL2
    PRODC_FL2
    Any help or tips will be greatly appreciated. Please note I'm working with more complex data and have simplified my question just to understand how to solve this.

    Just treat the two queries as tables, join them on DEPT and produce the results you want.
    with q1 as (
    select DEPT, sum(case PRODUCT_CODE when 'A' then 1 else 0 end) PRODA_FL1,
    sum(case PRODUCT_CODE when 'B' then 1 else 0 end) PRODB_FL1,
    sum(case PRODUCT_CODE when 'C' then 1 else 0 end) PRODC_FL1
    from SAMPLE_DATA where FLAG1 is not null group by DEPT),
    q2 as (
    select DEPT, sum(case PRODUCT_CODE when 'A' then 1 else 0 end) PRODA_FL2,
    sum(case PRODUCT_CODE when 'B' then 1 else 0 end) PRODB_FL2,
    sum(case PRODUCT_CODE when 'C' then 1 else 0 end) PRODC_FL2
    from SAMPLE_DATA where FLAG2 is not null group by DEPT;
    select q1.dept, proda_fl1, prodb_fl1, prodc_fl1, proda_fl2, prodb_fl2, prodc_fl2
    from q1, q2
    where q1.dept = q2.dept

  • Newbie Can I have an "IF Statement" in a WHERE clause?

    Example
    Select T.name,T.District,T.Dept
    from table T
    where IF myUnit=9998 THEN
    T.District='OZ'
    ELSIF myUnit=9997 THEN
    T.District='DE'
    ELSE
    T.Dept=myUnit
    END IF;
    ( myUnit is a variable selected by the user)
    TIA
    Steve

    test@ora>
    test@ora> --
    test@ora> with t as (
      2    select 'a0' name, '0Z' district, 9990 dept, 9998 myunit from dual union all
      3    select 'a1', 'XX', 9999, 9998 myunit from dual union all
      4    select 'a2', 'DE', 9998, 9997 myunit from dual union all
      5    select 'a3', 'YY', 9997, 9997 myunit from dual union all
      6    select 'a4', 'YY', 9999, 9999 myunit from dual union all
      7    select 'a5', 'YY', 9992, 9999 myunit from dual)
      8  --
      9  Select
    10    T.name,
    11    T.District,
    12    T.Dept,
    13    t.myunit
    14  from T
    15  where
    16    case myUnit
    17      when 9998 then T.District
    18      when 9997 then T.District
    19      else to_char(myUnit)
    20    end =
    21    case myUnit
    22      when 9998 then '0Z'
    23      when 9997 then 'DE'
    24      else to_char(T.Dept)
    25    end
    26  ;
    NAME                           DI       DEPT     MYUNIT
    a0                             0Z       9990       9998
    a2                             DE       9998       9997
    a4                             YY       9999       9999
    test@ora>
    test@ora>isotope

  • Dynamic query, where clause help

    Hi Folks,
    Using my code below to generate a query.
    When using more than one condition, I'm not sure how to work out where the AND goes.
    Can anyone please help?
    Thankyou
    WHERE
    <cfif stafffilter neq "">
    deviceofficer = #stafffilter#
    </cfif>
    <cfif assetid neq "">
    AND deviceasset = '#assetid#'
    </cfif>
    <cfif isdefined("noasset")>
    AND deviceasset = ''
    </cfif>
      <cfif  isdefined("noserial")>
    AND deviceserial = ''
    </cfif>
    <cfif serial neq "">
    AND deviceserial = '#serial#'
    </cfif>
    <cfif servicearea neq "">
    AND deviceservice = #servicearea#
    </cfif>
    ORDER by locationname

    I do this sort of thing:
    <cfset sWhereAnd = "WHERE">
    <cfif isdefined("colFilter")>
         #sWhereAnd# col = #colFilter#
        <cfset sWhereAnd = "AND">
    </cfif>
    <cfif isdefined("someOtherColFilter")>
         #sWhereAnd# someOtherCol = #someOtherColFilter#
        <cfset sWhereAnd = "AND">
    </cfif>
    [etc]
    (that's pseudocode... I'd never use isDefined() or not use a <cfqueryparam> tag for my parameter values).
    I don't like doing the somewhat popular WHERE 1=1 approach as it can force a full table scan (all rows in the table will match that, and each WHERE filter expression is applied to every row of the table being filtered), unless the DB optimises it out as noise (which is what it is).  To me it's using bad SQL to cut corners.
    To be honest though, I shy away from these generic sort of queries these days.  Most of the genericism never gets used, and more specific requirements are better implemented to meet the precise need.
    Adam

  • Case Statement in Crystal - Still need help

    I posted earlier today and I was told to use the formula below.   This formula works, however, it stops imputing information after the first condition is met.  I want the report to list ANY of the part numbers that meet the conditions below.  That is, I want the part numbers that exist between 213 and 242, 311 and 332 and 511 and 714.  Any part number that meets ANY of these conditions I want it to show up.
    However, instead the formula stops imputing part numbers after the first condition is met.  Is there any way to change the formula so that the report prints out part numbers that meet all of the conditions?
    How should I change the formula?
    THANK YOU!!
    {JobMaterials.jmmJobAssemblyID} = {?Pm-JJASM.JAASM}
    and
    {JobMaterials.jmmJobID} = {?Pm-JJASM.JAJOB}
    and
    Select {Parts.impPartID}
    Case "213" to "242": True
    Case "311" to "332": True
    Case "511" to "714" : True
    Default:
    False;

    Then your selection formula should be:
    {JobMaterials.jmmJobAssemblyID} = {?Pm-JJASM.JAASM}
    and
    {JobMaterials.jmmJobID} = {?Pm-JJASM.JAJOB}
    and
    Select mid(trim({JobMaterials.jmmPartID}),1,3)  ' Don't use {Parts.impPartID.  It's null here!
    Case "213" to "242" : True
    Case "311" to "332": True
    Case "511" to "714" : True
    Default:
    False;
    HTH,
    Carl
    P.S.,  I better get some serious points for hanging in this long!! 

  • Using if logic in the where clause of a select statement

    I have a select clause. And in the select clause there is a variable all_off_trt that can be 'Y' or 'N'.
    In the where clause I want to make it so that if a form variable is checked and all_off_trt is 'Y' then
    exclude it else if the form variable isn't checked then select it no matter what all_off_trt is.
    Is there any way to include either and if statement or a case statement within the where clause to acheive this? If not is there another way of doing it?
    Basically I am looking for a case statement like this
    case
    when all_off_trt = 'Y' and mail_para.code = 'Y' then false
    else true
    end
    Message was edited by:
    Tugnutt7

    Ok, so that really doesn't solve my problem. I have 3 different fields that I need to do that with. Each combining in a select statement to print an email list, as well as other thing limiting the where clause.
    This is currently what I have, tested and working 100%.
    cursor email_cur is
         select unique p.email,s.all_off_trt,s.all_deceased,s.no_enroll
    from participant p, trialcom t, ethics s
    where p.status='A'
    and p.surname=t.surname
    and p.initials=t.initials
    and s.trial_cd = t.tricom
    and s.centre = t.centre
    and p.email is not null
    and (t.centre in (select code from mail_parameters where user_name=user and mail_para='CENTRE')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='CENTRE'))
    and (t.tricom in (select code from mail_parameters where user_name=user and mail_para='TRIAL')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='TRIAL'))
    and (t.role in (select code from mail_parameters where user_name=user and mail_para='ROLE')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='ROLE'))
    and (p.country in (select code from mail_parameters where user_name=user and mail_para='COUNTRY')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='COUNTRY'))
    and (t.represent in (select code from mail_parameters where user_name=user and mail_para='REPRESENT')
    or 'XX' in (select code from mail_parameters where user_name=user and mail_para='REPRESENT'));
    This is in a program unit that runs when a button is clicked. At the end of that I need to add on the 3 case statements that help further narrow down the selection of emails to be printed. Then it prints the emails selected from this statement into a file. So it has to be done right in the select statement. The three table variables are the all_off_trt, all_deceased, and no_enroll. The form has 3 checkboxes. One for each, that when checked (giving the variable associated with the checkboxes a value of 'Y') excludes all emails that have a 'Y' in the coresponding table variable.

Maybe you are looking for