Using ISNULL in CASE statement

Hi,
I need to write a query that will gimme the resultsets based on a data comparison with some values, Those values that are null in the result set needs to be replaced with an empty string which can be obtained using ISNULL function. My question here is,
how to incorporate this in a SELECT statement that has CASE expression. I coded some thing like this but the result set for the column is returning zero instead of an empty string. The data type for this column ABC is varchar(10)
SELECT top 20
ABC
,CASE
WHEN ABC IN (8,9,10,13,14,15,16,17,19,20,21) THEN 10
WHEN ABC IN (31,32,33) THEN 30
WHEN ABC IN (53,52,54,55) THEN 50
WHEN ABC IN (61,62) THEN 60
WHEN (ABC IS NULL AND DEF IS NOT NULL) THEN 99
else ISNULL(ABC,'')
END
FROM XYZ
Any help is appreciated
Many Thanks,
Bhanu

SELECT top 20
ABC
,CASE
WHEN ABC IN (8,9,10,13,14,15,16,17,19,20,21) THEN '10'
WHEN ABC IN (31,32,33) THEN '30'
WHEN ABC IN (53,52,54,55) THEN '50'
WHEN ABC IN (61,62) THEN '60'
WHEN (ABC IS NULL AND DEF IS NOT NULL) THEN '99'
else ISNULL(ABC,'')
END
FROM XYZ

Similar Messages

  • Using null in CASE statements

    Hi,
    I have query with a case statement as follows:
    SELECT * FROM table
    WHERE
    CASE WHEN :variable like 'A' THEN column END is null
    WHEN :variable like 'B' THEN column END is not null;
    This works fine when returning "column is null" but not when "column is not null".
    Can I use a CASE statement like this?
    Thanks
    Lucy

    My data is too complicated to show, but depending on the value of the bind variable in the statement I want to return all the rows in a query where the data in a particular column is either null or not null.For example, looking at the EMP table, if my bind variable is whether I want to show the top manager or not, if set to 'Yes' I would like to return all rows of the EMP table where mgr is null (i.e. the one row where ename is 'KING'), if it were set to 'No' I would like to return all the rows where mgr is not null (i.e. all the other rows). The difference with my query is that the column contains strings, not numerics.
    I've used a CASE statement before where I equate the column to a particular value and that works fine, but I'm not sure how they deal with nulls. I've also tried DECODE and didn't get anywhere with that.
    Thanks
    Lucy

  • Use of decode/case statements

    I am trying to use a decode or case statement to check for a particular field code of 'SIP' and if that is the value I only want half of the production figure used in the calculations for that field ('SIP').
    The following code works well without the items commented out:
    SELECT ALL
    FINDER_WIS.PRODUCTION_HDR.END_TIME as prod_date,
    'SCD' as district,
    --decode(FINDER_WIS.FACILITY_FIELD_X.FIELD_CODE,'SIP',FINDER_WIS.PRODUCTION_DATA.VOLUME/2,FINDER_WIS.PRODUCTION_DATA) AS TEST_SIP,
    /*case when FINDER_WIS.FACILITY_FIELD_X.FIELD_CODE = 'SIP'
         then FINDER_WIS.PRODUCTION_DATA.VOLUME/2
              else FINDER_WIS.PRODUCTION_DATA.VOLUME
    end as fieldtest,*/
    round(SUM(NVL(FINDER_WIS.PRODUCTION_DATA.VOLUME,0))) as total_oil,
    ROUND(SUM(NVL(FINDER_WIS.PRODUCTION_DATA.VOLUME,0)) / TO_NUMBER(TO_CHAR(FINDER_WIS.PRODUCTION_HDR.END_TIME,'DD'))) AS BOPD
    FROM FINDER_WIS.PRODUCTION_HDR,
    FINDER_WIS.PRODUCTION_DATA,
    FINDER_WIS.FACILITY,
    FINDER_WIS.REPORTING_GROUP,
    FINDER_WIS.REPORTING_GROUP_DETAIL,
    FINDER_WIS.FACILITY_FIELD_X,
    SELECT distinct FINDER_WIS.FACILITY.FACILITY_S
    FROM FINDER_WIS.PRODUCTION_HDR,
    FINDER_WIS.PRODUCTION_DATA,
    FINDER_WIS.FACILITY,
    FINDER_WIS.REPORTING_GROUP,
    FINDER_WIS.REPORTING_GROUP_DETAIL
    WHERE (FINDER_WIS.PRODUCTION_HDR.ACTIVITY_TYPE = 'ALLOCATED'
    AND FINDER_WIS.PRODUCTION_HDR.TIME_PERIOD_TYPE = 'MONTH'
    AND FINDER_WIS.PRODUCTION_HDR.STATE_TYPE = 'STANDARD'
    AND FINDER_WIS.PRODUCTION_HDR.EXISTENCE_TYPE = 'ACTUAL'
    AND FINDER_WIS.PRODUCTION_DATA.MATERIAL_TYPE='OIL'
    and FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_TYPE = 'ASSET_TEAM'
    AND FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_ID ='SCD'
    and finder_wis.production_HDR.SOURCE = 'NEWWIS'
    AND FINDER_WIS.PRODUCTION_HDR.START_TIME BETWEEN :startdate_var AND :enddate_var)
    AND ((FINDER_WIS.PRODUCTION_DATA.PRODUCTION_HDR_S=FINDER_WIS.PRODUCTION_HDR.PRODUCTION_HDR_S)
    and (FINDER_WIS.PRODUCTION_HDR.FACILITY_S = FINDER_WIS.FACILITY.FACILITY_S)
    and (FINDER_WIS.PRODUCTION_HDR.START_TIME between FINDER_WIS.REPORTING_GROUP_DETAIL.start_time and nvl(FINDER_WIS.REPORTING_GROUP_DETAIL.end_time,'01-JAN-2010')
    or FINDER_WIS.PRODUCTION_HDR.end_TIME between FINDER_WIS.REPORTING_GROUP_DETAIL.start_time and nvl(FINDER_WIS.REPORTING_GROUP_DETAIL.end_time,'01-JAN-2010'))
    AND (FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_S = FINDER_WIS.REPORTING_GROUP_DETAIL.REPORTING_GROUP_S)
    AND (FINDER_WIS.FACILITY.FACILITY_S = FINDER_WIS.REPORTING_GROUP_DETAIL.FACILITY_S)))T
    WHERE (FINDER_WIS.PRODUCTION_HDR.ACTIVITY_TYPE = 'ALLOCATED'
    AND FINDER_WIS.PRODUCTION_HDR.TIME_PERIOD_TYPE = 'MONTH'
    AND FINDER_WIS.PRODUCTION_HDR.STATE_TYPE = 'STANDARD'
    AND FINDER_WIS.PRODUCTION_HDR.EXISTENCE_TYPE = 'ACTUAL'
    AND FINDER_WIS.PRODUCTION_DATA.MATERIAL_TYPE='OIL'
    and FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_TYPE = 'ASSET_TEAM'
    and finder_wis.production_HDR.SOURCE = 'NEWWIS'
    AND FINDER_WIS.PRODUCTION_HDR.START_TIME BETWEEN :startdate_var AND :enddate_var)
    AND ((FINDER_WIS.FACILITY.FACILITY_S = T.FACILITY_S)
    AND (FINDER_WIS.PRODUCTION_DATA.PRODUCTION_HDR_S=FINDER_WIS.PRODUCTION_HDR.PRODUCTION_HDR_S)
    AND FINDER_WIS.FACILITY_FIELD_X.UWI = FINDER_WIS.FACILITY.UWI
    AND FINDER_WIS.FACILITY_FIELD_X.FIELD_CODE NOT IN ('MW','BRM','PLG','SIP')
    and (FINDER_WIS.PRODUCTION_HDR.FACILITY_S = FINDER_WIS.FACILITY.FACILITY_S)
    and (FINDER_WIS.PRODUCTION_HDR.START_TIME between FINDER_WIS.REPORTING_GROUP_DETAIL.start_time and nvl(FINDER_WIS.REPORTING_GROUP_DETAIL.end_time,'01-JAN-2010')
    or FINDER_WIS.PRODUCTION_HDR.end_TIME between FINDER_WIS.REPORTING_GROUP_DETAIL.start_time and nvl(FINDER_WIS.REPORTING_GROUP_DETAIL.end_time,'01-JAN-2010'))
    AND (FINDER_WIS.REPORTING_GROUP.REPORTING_GROUP_S = FINDER_WIS.REPORTING_GROUP_DETAIL.REPORTING_GROUP_S)
    AND (FINDER_WIS.FACILITY.FACILITY_S = FINDER_WIS.REPORTING_GROUP_DETAIL.FACILITY_S))
    GROUP BY FINDER_WIS.PRODUCTION_HDR.END_TIME
    the results look like this but this is without the values for the 'SIP' field:
    PROD_DATE     DISTRICT     TOTAL_OIL BOPD
    31/10/2007     SCD     168009     5420
    30/11/2007     SCD     167339     5578
    31/12/2007     SCD     170277     5493
    31/01/2008     SCD     173677     5602
    29/02/2008     SCD     168498     5810
    31/03/2008     SCD     172689     5571
    30/04/2008     SCD     168180     5606
    31/05/2008     SCD     165448     5337
    30/06/2008     SCD     164631     5488
    31/07/2008     SCD     170073     5486
    31/08/2008     SCD     166520     5372
    30/09/2008     SCD     160321     5344
    When I try to add the decode or case statement, I get ORA-00979; not a Group By expression as the error.
    Can anyone assist me with this please?
    Thanks in advance

    Hi and welcome to the forum.
    Simply put the field names you use in your DECODE also in your GROUP BY and it should work:
    simple example:
    MHO%xe> with t as (
      2  select 1 col1, 1 col2 from dual union all
      3  select 1 col1, 1 col2 from dual union all
      4  select 2 col1, 2 col2 from dual union all
      5  select 3 col1, 3 col2 from dual union all
      6  select 4 col1, 4 col2 from dual
      7  )
      8  select col1
      9  ,      decode(col1, 1, col2*100, col2)
    10  ,      sum(col2)
    11  from   t
    12  group by col1 -->> NO col2 here...
    13  order by col1;
    ,      decode(col1, 1, col2*100, col2)
    FOUT in regel 9:
    .ORA-00979: not a GROUP BY expression
    Verstreken: 00:00:05.78
    MHO%xe> with t as (
      2  select 1 col1, 1 col2 from dual union all
      3  select 1 col1, 1 col2 from dual union all
      4  select 2 col1, 2 col2 from dual union all
      5  select 3 col1, 3 col2 from dual union all
      6  select 4 col1, 4 col2 from dual
      7  )
      8  select col1
      9  ,      decode(col1, 1, col2*100, col2)
    10  ,      sum(col2)
    11  from   t
    12  group by col1, col2
    13  order by col1;
          COL1 DECODE(COL1,1,COL2*100,COL2)  SUM(COL2)
             1                          100          2
             2                            2          2
             3                            3          3
             4                            4          4

  • How to use REGEXP for case statement

    Hello everyone, I'm very new here and am struggling with a using REGEXP in a case statement, OK I am using the REGEXP to find all strings that match a specific format for a particular brand of product, for example serial numbers, and I need to be able to say something like [case when(xx.brandid) = '123' then if xx.serialnumber REGEXP_LIKE(xx.serialnumber,'[A-za-z][A-za-z][A-za-z]\d{5,}[A-za-z]$') then 'TRUE' else 'FALSE' end "TRUE/FALSE".]
    Help would be greatly appreciated with this as I feel like I'm going backwards trying to figure this out
    Thanks in advance for any assistance.

    Like this?
    case
       when xx.brandid = '123' and
            regexp_like(xx.serialnumber,'[A-za-z][A-za-z][A-za-z]\d{5,}[A-za-z]$') then
          'TRUE'
       else
          'FALSE'
    end

  • Grouping using report query / Case statement in toplink

    I have following tables
    1. Student with columns id, gender
    2. Subject_Score with columns id, student_id, subject_id, score
    To get scores grouped by subject, I am doing
    ExpressionBuilder subjScoreBuilder = new ExpressionBuilder();
    ReportQuery query = new ReportQuery(SubjectScore.class);
    query.addAverage("average-score",subjScoreBuilder.get("score"));
    query.addGrouping(subjScoreBuilder.get("subjectId"));
    Vector responses = (Vector) serverSession.executeQuery(query);
    Float score = (Float) queryResult.get("average-score");
    This works fine. It gives avg score per each subject
    Now i want both in one query
    A) avg score per subject
    B) avg score per subject per gender
    I want to achive this in one query
    I am doing like:
    ExpressionBuilder subjScoreBuilder =new ExpressionBuilder(SubjectScore.class);
    ExpressionBuilder studentExpBuilder = new ExpressionBuilder(Student.class);
    Expression expression = subjScoreBuilder.get("studentid").equal(studentExpBuilder.get("id")));
    ReportQuery query = new ReportQuery(SubjectScore.class, expression);
    query.addAverage("average-score", subjScoreBuilder.get("score"));
    query.addGrouping( subjScoreBuilder.get("subjectId"));
    query.addGrouping( studentExpBuilder.get("gender"));
    This gives me avg scor per each subject per gender. i.e.
    it applies grouping on both subjectId & gender.
    This is fine.
    But I also want avg score per each subject (group on subject only) in same query.
    1. How can we achive it?
    2. is there something like Case statement in toplink?      
    Thanks a lot for any help.

    I believe in SQL you would need two queries to do this directly, so you will need to issue two queries.
    You could select the Count and Avg, this would give you all the data need to compute the Avg yourself.
    i.e.
    (count(male) * avg(male) + count(female) * avg(female)) / (count(male) + count(female))

  • Pivoting using Model Clause Vs pivoting using Aggregate Fun(Case) statement

    Hi,
    I just wanted to know which option is better for pivoting the data if the data is like:
    Grp1 Grp2 Day_week Sales
    1 1 Sun 200
    1 1 Mon 100
    1 2 Sun 1000
    and so on...
    The output should be:
    Grp1 Grp2 Sun Mon ......
    1 1 200 100.....
    1 2 1000 NULL....
    I have tested the same using sum(decode...) method and also model clause:
    select grp1, grp2, sum(decode(day_week,'SUN',sales)) SUNDAY , sum(decode(day_week,'MON',sales)) MONDAY from pivot
    group by grp1, grp2
    order by grp1, grp2
    select grp1, grp2, sun , mon, tue, wed, thr, fri, sat
    from pivot
    model -- UNIQUE SINGLE REFERENCE
    return updated rows
    partition by (grp1, grp2)
    dimension by ( day_week)
    measures( result, 0 mon, 0 tue, 0 wed, 0 thr,0 fri, 0 sat, 0 sun)
    RULES upsert
    mon[0]= sales['MON'],
    tue[0]= sales['TUE'],
    wed[0]= sales['WED'],
    thr[0]= sales['THR'],
    fri[0]= sales['FRI'],
    sat[0]= sales['SAT'],
    sun[0]= sales['SUN']
    ) order by grp1, grp2
    There are 4K records in the table. The first query is taking app (.125 seconds) and the second query (.230 seconds).
    Pls tell how the model clause can give better performance and I want to use it for pivoting in all my APIs.
    Regards
    Rajiv

    > I read somewhere while searching on net.
    And now you can't find it anymore? I wouldn't believe anything you read somewhere while searching on net, unless it has some kind of proof attached.
    > You pls tell is it so or it depends upon volume of data.
    Also i tested on some data and reults were better in
    case of using normal startegy rather than model.(case
    provided above).
    So you have tested it yourself already. The model clause is great in a few cases (string aggregation, calculating values based on calculated values), but this doesn't seem to be one of them. On 11g you might want to consider the PIVOT operator.
    Regards,
    Rob.

  • How do I use switch and case statements to fill more than one other field?

    Hi all,
    I'm new to the community.
    I'm trying to make an existing form more user friendly for my coworkers. I want to use a switch and case approach in a drop-down list field so that the selection fills two seperate other fields with different info related to the selection.
    I can already do this with one field, but if I add a second target field under an existing case the text doesn't appear there when I make the selection from the dropdown.
    Basically, I'm asking if I can do this:
    switch 
    (sNewSel){
       case "1": // Selection 1    Row2.Field1
    = "text for field 1";
        Row1.Field2 = "text for field 2"; 
        break;
    etc.
    It works if the "row1.field2" option isn't there, but not when it is present.
    Any takers?

    I'm not sure if I will be able to send you the form. There may be too much to redact.
    Would this last bit of code in the cell affect anything?
    if 
    (bEnableTextField)
    {Row2.Field1.access
    = "open"; // enable field
    Row2.Field1.caption.font.fill.color.value= "0,0,0"; // set caption to black
    That is, do I also need to repeat the same thing for the second target cell (Row1.Field2)?
    What would be possible hang ups that would prevent it from working correctly?
    Dave
    By the way, I'm not sure if my other attachment posted. I am trying again.

  • Using Decode Or Case Statement / Any Method

    Dear All,
    In my table Fields are
    EmpId
    TranYear
    TranMonth
    ApprovedBy
    ApprovedYear
    ApprovedMonth
    My Input parameters are
    1. TranYear
    2. TranMonth
    3. Tag1
    4. Tag2
    My requirement is
    Tag1 Input are 0,1,2
    Tag2 Inputs are 0,1,2
    If Tag1 is 0 then checking TranYear/TranMonth And
    Tag2 Is 0 Then ApprovedBy Is Not Null only
    Tag2 Is 1 Then ApprovedBy Is Null only
    Tag2 Is 2 Then both(Approved/unApproved)
    If Tag1 is 1 then checking ApprovedYear/ApprovedMonth And Tag2 Passing 0 Default
    If Tag1 is 2 then checking TranYear/TranMonth Or ApprovedYear/ApprovedMonth And
    Tag2 Is 0 Then ApprovedBy Is Not Null only
    Tag2 Is 1 Then ApprovedBy Is Null only
    Tag2 Is 2 Then both(Approved/unApproved)
    Based upon the input details select details

    dont quite understand your table structure requirement but it sounds like you want a conditional join.
    looks like you are always joining on the tran year tran month but according to your 2 flags decides the rest of the join
    I started something here where I am joining on the tran year / tran month then setting an indicator based on your flags
    then just select the rows where this indicator is true.
    anyway you can modify it to your needs
    WITH t AS (SELECT 1 EmpId,
                      EXTRACT (YEAR FROM TO_DATE ('2010', 'YYYY')) TranYear,
                      EXTRACT (MONTH FROM TO_DATE ('Oct', 'Mon')) TranMon,
                      10 approved_by,
                      EXTRACT (YEAR FROM TO_DATE ('2010', 'YYYY')) ApprovedYear,
                      EXTRACT (MONTH FROM TO_DATE ('Nov', 'Mon')) ApprovedMon
                 FROM DUAL
               UNION ALL
               SELECT 2,
                      EXTRACT (YEAR FROM TO_DATE ('2009', 'YYYY')),
                      EXTRACT (MONTH FROM TO_DATE ('Jul', 'Mon')),
                      11,
                      EXTRACT (YEAR FROM TO_DATE ('2009', 'YYYY')),
                      EXTRACT (MONTH FROM TO_DATE ('Dec', 'Mon'))
                 FROM DUAL),
         input AS (SELECT EXTRACT (YEAR FROM TO_DATE ('2010', 'YYYY')) TranYear,
                          EXTRACT (MONTH FROM TO_DATE ('Oct', 'Mon')) TranMon,
                          0 tag1,
                          0 tag2
                     FROM DUAL)
    SELECT *
      FROM (SELECT t.*,
                   tag1,
                   tag2,
                   CASE tag1 || '.' || tag2
                      WHEN '0.0'
                      THEN
                         CASE WHEN Approved_By IS NOT NULL THEN 1 ELSE 0 END -- if they are both 0 join on  Tran Year, Tran Month and Approved by not null
                      WHEN '0.1'
                      THEN
                         CASE WHEN Approved_By IS NULL THEN 1 ELSE 0 END -- if they are 0,1 then Tran Year, Tran Month and Approved by is null
                      WHEN '0.2'
                      THEN
                         0 -- CASE  --Then both(Approved/unApproved)  i Don't know what this means
                    /* WHEN '1.0' then whatever
                        when  '1.1' then whatever
                        when '1.2  then whatever
                      ELSE
                         0
                   END
                      ind
              FROM t, input
             WHERE t.TranYear = input.TranYear AND t.TranMon = input.TranMon)
    WHERE ind = 1

  • Using case statement in OWB expression builder

    Hi All,
    We are using OWB version 10.2.0.1.0. While using the below case statement We are getting the validation message as 'The expression is not properly formed'.
    Case statement used in expression builder:
    case when (INGRP1.CHARGETYPE in ('O','F') or INGRP1.TARIFF_GROUP in ('SMSINT','MMSINT')or ( INGRP1.CALL_TYPE = '002' and INGRP1.TARIFF_GROUP = 'MTV'))
    then
    (select call_zone_reltn_key from call_zone_reltn where
    call_zone_cd=substr(case
                   when substr( INGRP1.B_SUBNO,1,2)='00'
                   then
                   substr( INGRP1.B_SUBNO,3)
                   else substr( INGRP1.B_SUBNO,1)
                   end,1,length(call_zone_cd))and rownum=1)
    else -1
    end
    Kindly help me out in fixing this error or suggest any alternate way to use the above query in OWB expression builder.
    Thanks,
    Kabilan

    946887 wrote:
    Hi All,
    We are using OWB version 10.2.0.1.0. While using the below case statement We are getting the validation message as 'The expression is not properly formed'.
    Did you try to deploy the mapping ? Some time the expression validator gives wrong error messege.
    Try to deploy the mapping and see if you are still getting this issue
    Case statement used in expression builder:
    case when (INGRP1.CHARGETYPE in ('O','F') or INGRP1.TARIFF_GROUP in ('SMSINT','MMSINT')or ( INGRP1.CALL_TYPE = '002' and INGRP1.TARIFF_GROUP = 'MTV'))
    then
    (select call_zone_reltn_key from call_zone_reltn where
    call_zone_cd=substr(case
                   when substr( INGRP1.B_SUBNO,1,2)='00'
                   then
                   substr( INGRP1.B_SUBNO,3)
                   else substr( INGRP1.B_SUBNO,1)
                   end,1,length(call_zone_cd))and rownum=1)
    else -1
    end
    Kindly help me out in fixing this error or suggest any alternate way to use the above query in OWB expression builder.
    Thanks,
    Kabilan

  • CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL

    제품 : PL/SQL
    작성날짜 : 2001-11-13
    CASE STATEMENTS AND CASE EXPRESSIONS IN ORACLE9I PL/SQL
    =======================================================
    PURPOSE
    아래의 자료는 Case 문에서 oracle 8.1.7과 Oracle 9i의 New Feature로 8.1.7에서는
    sqlplus 에서만 가능했고, 9i 부터는 pl/sql 까지 가능하다.
    Explanation
    1. Oracle 8.1.7 Feature
    Oracle 8.1.7 에서 Case 문은 Decode 문과 유사하지만, 기존의 decode 문을 쓰는 것보다
    더 많은 확장성과 Logical Power와 좋은 성능을 제공한다. 주로 나이와 같이 category 별로
    나눌때 주로 사용하고 Syntex는 아래와 같다.
    CASE WHEN <cond1> THEN <v1> WHEN <cond2> THEN <v2> ... [ELSE <vn+1> ] END
    각각의 WHEN...THEN 절의 argument 는 255 까지 가능하고 이 Limit를 해결하려면
    Oracle 8i Reference를 참조하면 된다.
    The maximum number of arguments in a CASE expression is 255, and each
    WHEN ... THEN pair counts as two arguments. To avoid exceeding the limit of 128 choices,
    you can nest CASE expressions. That is expr1 can itself be a CASE expression.
    Case Example : 한 회사의 모든 종업원의 평균 봉급을 계산하는데 봉급이 $2000보다 작은경우
    2000으로 계산을 하는 방법이 pl/sql을 대신하여 case function을 사용할 수 있다.
    SELECT AVG(CASE when e.sal > 2000 THEN e.sal ELSE 2000 end) FROM emp e;
    Case Example : 나이를 column으로 가지고 있는 customer table을 예로 들어보자.
    SQL> SELECT
    2 SUM(CASE WHEN age BETWEEN 70 AND 79 THEN 1 ELSE 0 END) as "70-79",
    3 SUM(CASE WHEN age BETWEEN 80 AND 89 THEN 1 ELSE 0 END) as "80-89",
    4 SUM(CASE WHEN age BETWEEN 90 AND 99 THEN 1 ELSE 0 END) as "90-99",
    5 SUM(CASE WHEN age > 99 THEN 1 ELSE 0 END) as "100+"
    6 FROM customer;
    70-79 80-89 90-99 100+
    4 2 3 1
    1 SELECT
    2 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
    3 WHEN age BETWEEN 80 and 89 THEN '80-89'
    4 WHEN age BETWEEN 90 and 99 THEN '90-99'
    5 WHEN age > 99 THEN '100+' END) as age_group,
    6 COUNT(*) as age_count
    7 FROM customer
    8 GROUP BY
    9 (CASE WHEN age BETWEEN 70 AND 79 THEN '70-79'
    10 WHEN age BETWEEN 80 and 89 THEN '80-89'
    11 WHEN age BETWEEN 90 and 99 THEN '90-99'
    12* WHEN age > 99 THEN '100+' END)
    SQL> /
    AGE_G AGE_COUNT
    100+ 1
    70-79 4
    80-89 2
    90-99 3
    Example
    2. Oracle 9i Feature
    Oracle 9i부터는 pl/sql에서도 case문을 사용할 수 있으면 이것은
    복잡한 if-else 구문을 없애고, C언어의 switch문과 같은 기능을 한다.
    아래의 9i pl/sql Sample 및 제약 사항을 보면 아래와 같다.
    Sample 1:
    A simple example demonstrating the proper syntax for a case
    statement
    using a character variable as the selector. See the section entitled
    'Restrictions' at the end of this article for details on which PLSQL
    datatypes may appear as a selector in a case statement or
    expression.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    achar char(1) := '&achar';
    begin
    case achar
    when 'A' then dbms_output.put_line('The description was Excellent');
    when 'B' then dbms_output.put_line('The description was Very Good');
    when 'C' then dbms_output.put_line('The description was Good');
    when 'D' then dbms_output.put_line('The description was Fair');
    when 'F' then dbms_output.put_line('The description was Poor');
    else dbms_output.put_line('The description was No such Grade');
    end case;
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 2:
    A simple example demonstrating the proper syntax for a case
    expression
    using a character variable as the selector. See the section entitled
    'Restrictions' at the end of this article for details on which PLSQL
    datatypes may appear as a selector in a case statement or
    expression.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    achar char(1) := '&achar';
    description varchar2(20);
    begin
    description :=
    case achar
    when 'A' then 'Excellent'
    when 'B' then 'Very Good'
    when 'C' then 'Good'
    when 'D' then 'Fair'
    when 'F' then 'Poor'
    else 'No such grade'
    end;
    dbms_output.put_line('The description was ' || description);
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    NOTE: The above simple samples demonstrate two subtle differences in the
    syntax
    required for case statements and expressions.
    1) A case STATEMENT is terminated using the 'end case' keywords; a
    case
    EXPRESSION is terminated using only the 'end' keyword.
    2) Each item in a case STATEMENT consists of one or more
    statements, each
    terminated by a semicolon. Each item in a case expression
    consists of
    exactly one expression, not terminated by a semicolon.
    Sample 3:
    Sample 1 demonstrates a simple case statement in which the selector
    is
    compared for equality with each item in the case statement body.
    PL/SQL
    also provides a 'searched' case statement as an alternative; rather
    than
    providing a selector and a list of values, each item in the body of
    the
    case statement provides its own predicate. This predicate can be any
    valid boolean expression, but only one case will be selected.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    achar char(1) := '&achar';
    begin
    case
    when achar = 'A' then dbms_output.put_line('The description was
    Excellent');
    when achar = 'B' then dbms_output.put_line('The description was Very
    Good');
    when achar = 'C' then dbms_output.put_line('The description was
    Good');
    when achar = 'D' then dbms_output.put_line('The description was
    Fair');
    when achar = 'F' then dbms_output.put_line('The description was
    Poor');
    else dbms_output.put_line('The description was No such Grade');
    end case;
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 4:
    This sample demonstrates the proper syntax for a case expression of
    the
    type discussed in Sample 3 above.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    achar char(1) := '&achar';
    description varchar2(20);
    begin
    description :=
    case
    when achar = 'A' then 'Excellent'
    when achar = 'B' then 'Very Good'
    when achar = 'C' then 'Good'
    when achar = 'D' then 'Fair'
    when achar = 'F' then 'Poor'
    else 'No such grade'
    end;
    dbms_output.put_line('The description was ' || description);
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 5:
    This sample demonstrates the use of nested case statements. It is
    also
    permissable to nest case expressions within a case statement (though
    it
    is not demonstrated here), but nesting of case statements within a
    case
    expression is not possible since statements do not return any value.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    anum1 number := &anum1;
    anum2 number := &anum2;
    answer number;
    begin
    case anum1
    when 1 then case anum2
    when 1 then answer := 10;
    when 2 then answer := 20;
    when 3 then answer := 30;
    else answer := 999;
    end case;
    when 2 then case anum2
    when 1 then answer := 15;
    when 2 then answer := 25;
    when 3 then answer := 35;
    else answer := 777;
    end case;
    else answer := 555;
    end case;
    dbms_output.put_line('The answer is ' || answer);
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 6:
    This sample demonstrates nesting of case expressions within another
    case
    expression. Note again the absence of semicolons to terminate both
    the
    nested case expression and the individual cases of those
    expressions.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    declare
    anum1 number := &anum1;
    anum2 number := &anum2;
    answer number;
    begin
    answer :=
    case anum1
    when 1 then case anum2
    when 1 then 10
    when 2 then 20
    when 3 then 30
    else 999
    end
    when 2 then case anum2
    when 1 then 15
    when 2 then 25
    when 3 then 35
    else 777
    end
    else 555
    end;
    dbms_output.put_line('The answer is ' || answer);
    end;
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Although PL/SQL anonymous blocks have been used in all of the examples
    so far,
    case statements and expressions can also be used in procedures,
    functions, and
    packages with no changes to the syntax.
    The following samples are included for completeness and demonstrate the
    use of
    case statements and/or expressions in each of these scenarios.
    Sample 7:
    This sample demonstrates use of a case statement in a stored
    procedure.
    Note that this sample also demonstrates that it is possible for each
    of
    the items in the case body to consist of more than one statement.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    create or replace procedure testcasestmt ( anum IN number ) is
    begin
    case
    when anum = 1 then dbms_output.put_line('The number was One');
    dbms_output.put_line('In case 1');
    when anum = 2 then dbms_output.put_line('The number was Two');
    dbms_output.put_line('In case 2');
    when anum = 3 then dbms_output.put_line('The number was Three');
    dbms_output.put_line('In case 3');
    when anum = 4 then dbms_output.put_line('The number was Four');
    dbms_output.put_line('In case 4');
    when anum = 5 then dbms_output.put_line('The number was Five');
    dbms_output.put_line('In case 5');
    else dbms_output.put_line('The description was Invalid input');
    dbms_output.put_line('In the else case');
    end case;
    end;
    exec testcasestmt(&anum);
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 8:
    This sample demonstrates the use of a case statement in a stored
    package.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    create or replace package testpkg2 is
    procedure testcasestmt ( anum IN number );
    function testcasestmt_f ( anum IN number ) return number;
    end testpkg2;
    create or replace package body testpkg2 is
    procedure testcasestmt ( anum IN number ) is
    begin
    case
    when anum = 1 then dbms_output.put_line('The number was One');
    dbms_output.put_line('In case 1');
    when anum = 2 then dbms_output.put_line('The number was Two');
    dbms_output.put_line('In case 2');
    when anum = 3 then dbms_output.put_line('The number was Three');
    dbms_output.put_line('In case 3');
    when anum = 4 then dbms_output.put_line('The number was Four');
    dbms_output.put_line('In case 4');
    when anum = 5 then dbms_output.put_line('The number was Five');
    dbms_output.put_line('In case 5');
    else dbms_output.put_line('The description was Invalid input');
    dbms_output.put_line('In the else case');
    end case;
    end;
    function testcasestmt_f ( anum IN number ) return number is
    begin
    case
    when anum = 1 then dbms_output.put_line('The number was One');
    dbms_output.put_line('In case 1');
    when anum = 2 then dbms_output.put_line('The number was Two');
    dbms_output.put_line('In case 2');
    when anum = 3 then dbms_output.put_line('The number was Three');
    dbms_output.put_line('In case 3');
    when anum = 4 then dbms_output.put_line('The number was Four');
    dbms_output.put_line('In case 4');
    when anum = 5 then dbms_output.put_line('The number was Five');
    dbms_output.put_line('In case 5');
    else dbms_output.put_line('The description was Invalid input');
    dbms_output.put_line('In the else case');
    end case;
    return anum;
    end;
    end testpkg2;
    exec testpkg2.testcasestmt(&anum);
    variable numout number
    exec :numout := testpkg2.testcasestmt_f(&anum);
    print numout
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    Sample 9:
    This sample demonstrates the use of a case expression in a stored
    package.
    - - - - - - - - - - - - - - - - Code begins here - - - - - - - - - - - -
    set serveroutput on
    create or replace package testpkg is
    procedure testcase ( anum IN number );
    function testcase_f ( anum IN number ) return number;
    end testpkg;
    create or replace package body testpkg is
    procedure testcase ( anum IN number ) is
    anumber number := anum;
    anothernum number;
    begin
    anothernum :=
    case
    when anumber = 1 then anumber + 1
    when anumber = 2 then anumber + 2
    when anumber = 3 then anumber + 3
    when anumber = 4 then anumber + 4
    when anumber = 5 then anumber + 5
    else 999
    end;
    dbms_output.put_line('The number was ' || anothernum);
    end;
    function testcase_f ( anum IN number ) return number is
    anumber number := anum;
    anothernum number;
    begin
    anothernum :=
    case
    when anumber = 1 then anumber + 1
    when anumber = 2 then anumber + 2
    when anumber = 3 then anumber + 3
    when anumber = 4 then anumber + 4
    when anumber = 5 then anumber + 5
    else 999
    end;
    dbms_output.put_line('The number was ' || anothernum);
    return anothernum;
    end;
    end testpkg;
    variable numout number
    exec testpkg.testcase(&anum);
    exec :numout := testpkg.testcase_f(&anum);
    print numout
    - - - - - - - - - - - - - - - - Code ends here - - - - - - - - - - - -
    제약 사항
    다음의 databasetype은 case 문에서 지원되지 않는다.
    BLOB
    BFILE
    VARRAY
    Nested Table
    PL/SQL Record
    PL/SQL Version 2 tables (index by tables)
    Object type (user-defined type)
    All of these types except for object types face a similar restriction
    even for if statements (i.e. they cannot be compared for equality directly) so this is unlikely to change for these types. Lack of support for object types is simply an implementation restriction which may be relaxed in future releases.
    Reference Ducumment
    Oracle 8.1.7 Manual
    NOTE:131557.1

    I have done the following code but doesn't
    like the statement of - "case(butNext)". What do you mean "doesn't like" -- did you get an error message?
    I'm guessing it won't compile because you're trying to switch on a Button.
    I tried something
    like "g.fillOval(100,50,70,90, BorderLayout.NORTH)"...no that doesn't make sense. You only use BorderLayout.NORTH when you're adding components to a BorderLayout layout manager. An oval is not a component and fillOval isn't adding a component and Graphics is not a Panel or layout manager.
    Would appreciate it if someone could tell me how to position
    shapes using the graohic method. I think the problem is that you're confusing shapes with components.

  • How to use decode or case function in this?

    Hi,
    I want to implement this condition in a query without using any user defined functions
    1.if (T_fees = 'ABC' then if (p_fees>0) then nvl(p_fees,0) else (p_fees + a_fees) else 0)
    2. if(g_fees <> (if t_fees = 'ABC' then if (p_fees>0) then nvl(p_fees,0) else (p_fees)
    else 0
    Is it possible to use any nested 'CASE' statement ?
    This is very urgent...
    Regards,
    Shilpa

    Hi,
    Is it possible to use any nested 'CASE' statement ?Yes it it possible.
    "afiedt.buf" 7 lines, 89 characters
      1  SELECT sysdate FROM DUAL
      2  WHERE 1 = (CASE WHEN 1=1  AND 2=2 THEN
      3             1
      4       ELSE
      5             2
      6*     END)
    SQL>/
    SYSDATE
    07-AUG-06
    1 row selected.
    "afiedt.buf" 11 lines, 139 characters
      1  SELECT sysdate FROM DUAL
      2  WHERE 1 = (CASE WHEN 1=1  AND 2=2 THEN
      3             CASE WHEN 3=3 AND 4=4 THEN
      4                     1
      5             ELSE
      6                     0
      7             END
      8       ELSE
      9             0
    10*     END)
    SQL>/
    SYSDATE
    07-AUG-06
    1 row selected.
    You can implement your logic.
    Regards

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

  • Problem to identify values in a case statement.

    Hi Friends,
    Total number of records in my report should be divided by 5 and to be alloted into 5 grades in Grade column.
    This is what I have done so far in my report with following layout.
    S.No - Col A - Col B - Col C - Grade ( Colums A,B,C will be hidden in Report)
    *****Column C will have only 5 values at max ( 0.0, 0.2, 0.4, 0.6, 0.8).The below example is for 6 records in a report.The same will be applied for 7,8,9,10 records.
    In column A: MAX(cast(RCOUNT(1) AS DOUBLE))/5 ( Ex : 6/5 = 1.2)
    In Column B: Truncate(MAX(cast (RCOUNT(1) as double)/5), 0) ( Ex : 6/5 = 1.0)
    In Column C: Col A- Col B ( EX:1.2 - 1.0 =0.2)
    (MAX(cast(RCOUNT(1) AS DOUBLE))/5 - Truncate(MAX(cast (RCOUNT(1) as double)/5), 0))
    Now In Grade coulum I want to use this column C to Grade the records with case statements in it.
    I am trying to use the following case statement for Grade Coulmn
    Case
    when (MAX(cast(RCOUNT(1) AS DOUBLE))/5 - Truncate(MAX(cast (RCOUNT(1) as double)/5), 0)) = 0.0 then .........
    when (MAX(cast(RCOUNT(1) AS DOUBLE))/5 - Truncate(MAX(cast (RCOUNT(1) as double)/5), 0)) = 0.2 then .............
    when (MAX(cast(RCOUNT(1) AS DOUBLE))/5 - Truncate(MAX(cast (RCOUNT(1) as double)/5), 0)) = 0.4 then .............
    when (MAX(cast(RCOUNT(1) AS DOUBLE))/5 - Truncate(MAX(cast (RCOUNT(1) as double)/5), 0)) = 0.6 then ........
    when (MAX(cast(RCOUNT(1) AS DOUBLE))/5 - Truncate(MAX(cast (RCOUNT(1) as double)/5), 0)) = 0.8 then .....
    end
    Case statement works gud for 0.0 but not for other 4 values.
    It is unable to identify other 4values.
    Please tell me, how can I make case statement work for all values in above scenario.
    Thanks in Advance,
    Varsha.
    Edited by: Varsha on Nov 28, 2010 6:23 PM

    In column A: MAX(cast(RCOUNT(1) AS DOUBLE))/5 ( Ex : 6/5 = 1.2)
    In Column B: Truncate(MAX(cast (RCOUNT(1) as double)/5), 0) ( Ex : 6/5 = 1.0)
    In Column C: Col A- Col B ( EX:1.2 - 1.0 =0.2)
    (MAX(cast(RCOUNT(1) AS DOUBLE))/5 - Truncate(MAX(cast (RCOUNT(1) as double)/5), 0))Change the formula a bit by adding the by dim value for the MAX column.
    Column A: MAX(cast(RCOUNT(1) AS DOUBLE) by DimTable.Column)/5
    Column B: Truncate(MAX(cast (RCOUNT(1) as double) by DimTable.Column)/5, 0)
    Column C: MAX(cast(RCOUNT(1) AS DOUBLE) by DimTable.Column)/5 - Truncate(MAX(cast (RCOUNT(1) as double) by DimTable.Column)/5, 0)
    now write a case statement on top column c, based on your logic every 5th record will have a value 0.0
    Note: Dimtable.column is the table.column for which the row count is taken.
    Thanks,
    Vino

  • Case statement not working in rpd

    Hi Gurus,
    I am giving case statement for the exchange rate column#1 from original exchange rate column , the data of column is like
    0.0
    0.0
    0.1
    0.2
    1.2
    1.3
    1.4
    so here i dont want 0.0 instead of that i want 1.0 so whenever in next derived column i will calculate it would be this derived exchange rate#1 * inv amt = desired amt
    for the same I used different diff. case statement but still 0.0 is not going , I am giving like
    1) CASE WHEN BookingsBacklog."Fact USJ Sales Billing"."Loc Exchange Rate" = 0.0 THEN BookingsBacklog."Fact USJ Sales Billing"."Loc Exchange Rate" * 1.0 ELSE BookingsBacklog."Fact USJ Sales Billing"."Loc Exchange Rate" END
    2) CASE WHEN BookingsBacklog."Fact USJ Sales Billing"."Loc Exchange Rate" = 0.0 THEN 1.0 ELSE BookingsBacklog."Fact USJ Sales Billing"."Loc Exchange Rate" END
    nothing is working , result remains same, any quick help would be apprciated
    Thanks,

    Once again, could you write all information, like I described here my example.
    When tried the same it works.
    TABLE.COLUMN1 is from dimension.
    TABLE.COLUMN1 is DOUBLE in the physical layer (in Oracle it is NUMBER(8,2)) and view/data gives:
    TABLE.COLUMN1
    12.99
    0.00
    0.20
    In the RPD I made new logical columns.
    EXPR:
    CASE WHEN "Presentation area".TABLE.COLUMN1 = 0.0 THEN 1.0 ELSE "Presentation area".TABLE.COLUMN1 END
    EXPR2:
    CASE WHEN "Presentation area".TABLE.COLUMN1 = 0 THEN 1 ELSE "Presentation area".TABLE.COLUMN1 END
    Test in Answers:
    COLUMN1----EXPR----EXPR2
    12.99---------12.99----12.99
    0.00-------------1.0--------1.0
    0.20------------0.20------0.20
    I leaved data format on the column properties as default (override default data format not checked).
    I don't see where is the problem.
    Regards
    Goran
    http://108obiee.blogspot.com

  • CASE Statement order of precedence

    The question i have is in regards to the CASE statement.
    If i have the following CASE statement in a calculation, and use the calculation to populate the column header, it returns 2 columns, one for 'Mexico' and one for 'Exclude' - That is good
    Statement 1:
    CASE WHEN ( "Customers (Sales History)".Country = 'MX' )
    THEN 'Mexico'
    ELSE 'Exclude'
    END
    So i have sucessfully extracted out sales from Mexico, now i want break those sales into 2 categories, 'Primary' and 'Secondary'. If i use the below case statement, I was expecting to get 3 column headers, one for 'Primary' one for 'Secondary' and one for 'Exclude', but instead I only get 1 column header for exclude. Im sure it has something to do with order of precedence, but could someone explain the logic of why discover handles it this way, and how to get around it?
    Statement 2:
    CASE WHEN ( "Customers (Sales History)".Country = 'MX' )
    THEN
    CASE WHEN ( Item Groups.Sales Type Id <> 3)
    THEN 'Primary'
    ELSE 'Secondary'
    END
    ELSE 'Exclude'
    END
    As a side note, if i use statement 2 and set a condition "Statement 2 <> 'Exclude'" , the result will be the columns 'Primary' & 'Secondary'
    Thanks
    Chris

    Hi,
    Can anyone tell me how to use a fast formula in discoverer-desktop [for reporting]. Currently, we have a disco-report that calcuates the 'monthly salary', but we don't want to use that. Instead, we have a custom fast-formula [xx_oab_monthly_salary] which has the conditions and calculations that we need.
    I want to use that formula in discoverer-desktop directly and get the monthly-salary.. i.e., someone needs to create a folder under the business area and add it i believe.. the formula internally calls a function.
    when i checked about this with my dba - he said, he can add the 'function', but not the formula. and i need to write the calculation part...
    does anyone know how to add it...there shud a way right...
    i do not have access to the technical-stuff here..
    someone said ["you can wrap the FF_EXEC.run_formula call into your own pl/sql function and map this function into the EUL so that the formula can be called from a workbook.", but this talks about pl/sql-do we need pl/sql
    for this].
    also, someone else said [ some fast formulas need specific contexts to be set. Depending on whether the fast formula below the only fast formula that you want to recreate in Discoverer.
    For a single formula, in general my recommendation is to recreate the fast formula instead of using the ff_exec call].
    any quick answers greatly appreciate..
    thx,

Maybe you are looking for