Select in CASE statement or in IF-THEN-ELSE

I have been struggling for a week with a problem and still can't solve the way I want.
Given four text fields in page : p1_name, p1_place_name, p1_place_number and p1_place_init_letter - where user types text and press 'Search' button to see the results.
p1_name finds results in table EMPLOYEES
p1_place_name, p1_place_number and p1_place_init_letter find results in table PLACES
the two tables are linked by id_place field
I would like reports to be shown depending on search results:
- if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist AND EMPLOYEES.id_place = PLACES.id_place then a single report shows only employee row
- if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist AND EMPLOYEES.id_place # PLACES.id_place then two reports showing 1) employees with name = :p1_name and 2) places with name, number and init_letter = :p1_.....
- if p1_name not exists and (p1_place_name and p1_place_number and p1_place_init_letter) exist then a message with 'NO EMPLOYEE' and report shows only places where name, number and init_letter = :p1_.....
- if p1_name exists and (p1_place_name and p1_place_number and p1_place_init_letter) not exist then report shows only employee row where name = :p1_name and message with 'NO PLACE'
- if p1_name not exists and (p1_place_name and p1_place_number and p1_place_init_letter) not exist then messages 'NO EMPLOYEE' and 'NO PLACE'
I do NOT know if it is possible, and if it is, then what do I have to use : IF - THEN - ELSE or CASE ?
I tried to build HTML report region conditionally shown for each situation, but they do not work the way I want.
Could you please help me ?
Thank you in advance !

Agree with Dan. Use a dedicated report region for a unique query. Use a rendering condition to determine if that reporting region must be rendered (i.e. whether or not that reporting query must be executed ).
The alternative is creating a function that constructs the SQL query dynamically, based on the user supplied values for page items. Use the function as the source for the reporting region, instead of a SQL statement. (this is similar to creating a ref cursor for a client, minus the actual step to create the ref cursor - instead the source SQL for that ref cursor is returned).
Also consider asking your Apex questions in the dedicated Apex forum on OTN.

Similar Messages

  • Should I use a CASE statement to accomplish or something else

    So I have the following query right now
    select *
        --bulk collect into possession_leaders
        from
               select    distinct
                         opt.team_id,
                         sch.game_code,
                         sch.game_code_1032,
                         sch.home_team_id_1032,
                         sch.home_team_id,
                         sch.home_team_name,
                         sch.home_team_nickname,
                         sch.home_team_abbrev,
                         sch.away_team_id_1032,
                         sch.away_team_id,
                         sch.away_team_name,
                         sch.away_team_nickname,
                         sch.away_team_abbrev,
                         opt.possession,
                         rank () over (order by possession desc) as rankings_order
              from 
                       customer_data.cd_soccer_schedule sch,
                       soccer.soccer_optical_team_gm_stats opt
              where    sch.game_code = opt.game_code
              and      sch.season_id = 200921
              and      opt.possession is not null
              order by rankings_order asc
            )It outputs the following (Sorry for it being so cramped together):
    **Note: Columns are in the same order as the query, I didn't post the column names b/c everything would look even sloppier then it does
    1     5358     870986     2009050606     6     5359     Kansas City     Wizards     KC     5     5358     D.C.     United     DC     69.5%     1
    2     5354     870945     2009040501     1     5354     Chicago     Fire     Chi     10     5362     New York     Red Bulls     RB     58.1%     2
    3     5721     870983     2009050211     11     5363     San Jose     Earthquakes     SJ     17     5721     Chivas USA          Chv     56%     3
    4     5360     870984     2009050207     7     5360     Los Angeles     Galaxy     LA     10     5362     New York     Red Bulls     RB     55.6%     4
    5     5361     870961     2009041705     5     5358     D.C.     United     DC     9     5361     New England     Revolution     NE     55.4%     5
    6     5362     870988     2009050810     10     5362     New York     Red Bulls     RB     11     5363     San Jose     Earthquakes     SJ     50.1%     6
    7     5363     870988     2009050810     10     5362     New York     Red Bulls     RB     11     5363     San Jose     Earthquakes     SJ     49.9%     7
    8     5358     870961     2009041705     5     5358     D.C.     United     DC     9     5361     New England     Revolution     NE     44.6%     8
    9     5362     870984     2009050207     7     5360     Los Angeles     Galaxy     LA     10     5362     New York     Red Bulls     RB     44.4%     9
    10     5363     870983     2009050211     11     5363     San Jose     Earthquakes     SJ     17     5721     Chivas USA          Chv     44%     10
    11     5362     870945     2009040501     1     5354     Chicago     Fire     Chi     10     5362     New York     Red Bulls     RB     41.9%     11
    12     5359     870986     2009050606     6     5359     Kansas City     Wizards     KC     5     5358     D.C.     United     DC     30.5%     12What i'm trying to do is basically have the output formated so that when the team_id column matches the either the home_team_id or away_team_id colum i want the following columns to be renamed as:
    so if team_id = home_team_id for example then I want the following...
    sch.home_team_id_1032 as team_code_1032,
    sch.home_team_id as team_code,
    sch.home_team_name as team_name,
    sch.home_team_nickname as team_nickname,
    sch.home_team_abbrev as team_abbrev
    and then the away team columns would be...
    sch.away_team_id_1032 as opp_team_code_1032,
    sch.away_team_id as opp_team_code,
    sch.away_team_name as opp_team_name,
    sch.away_team_nickname as opp_team_nickname,
    sch.away_team_abbrev as opp_team_abbrev
    and same thing vice versa if the team_id column matches the away_team_id
    How is the best way to go about this? W/a case statement? and if so can someone please post the logic/

    Hi,
    user652714 wrote:
    So I have the following query right now
    select *
    --bulk collect into possession_leaders
    from
    select    distinct
    opt.team_id,
    sch.game_code,
    sch.game_code_1032,
    sch.home_team_id_1032,
    sch.home_team_id,
    sch.home_team_name,
    sch.home_team_nickname,
    sch.home_team_abbrev,
    sch.away_team_id_1032,
    sch.away_team_id,
    sch.away_team_name,
    sch.away_team_nickname,
    sch.away_team_abbrev,
    opt.possession,
    rank () over (order by possession desc) as rankings_order
    from 
    customer_data.cd_soccer_schedule sch,
    soccer.soccer_optical_team_gm_stats opt
    where    sch.game_code = opt.game_code
    and      sch.season_id = 200921
    and      opt.possession is not null
    order by rankings_order asc
    )It outputs the following (Sorry for it being so cramped together):
    **Note: Columns are in the same order as the query, I didn't post the column names b/c everything would look even sloppier then it doesAre you sure?
    The 6th column in the query is home_team name; the 6th column of the output has values like 5359 and 5354. Did you perhaps duplicate the rankings_iorder column at the beginning of the results?
    Why don't you simplify the problem. Instead of 15 or 16 columns, 10 of which are twins (5 pairs of 2 columns), why don't you post a problem with 6 columns, 4 of which are twins? Pick short columns, such as home_team_abbrev rather than home_team_name.
    Adding the other columns later should be easy; merely a matter of coping one of the columns ion the solution.
    Whenever you have a problem, post some sample data and the results you want from that data.
    In this case, the sample data can be about 6 columns from the result set below. I'll bet you can make a good sample set with fewer than 12 rows, also.
    1     5358     870986     2009050606     6     5359     Kansas City     Wizards     KC     5     5358     D.C.     United     DC     69.5%     1
    2     5354     870945     2009040501     1     5354     Chicago     Fire     Chi     10     5362     New York     Red Bulls     RB     58.1%     2
    3     5721     870983     2009050211     11     5363     San Jose     Earthquakes     SJ     17     5721     Chivas USA          Chv     56%     3
    4     5360     870984     2009050207     7     5360     Los Angeles     Galaxy     LA     10     5362     New York     Red Bulls     RB     55.6%     4
    5     5361     870961     2009041705     5     5358     D.C.     United     DC     9     5361     New England     Revolution     NE     55.4%     5
    6     5362     870988     2009050810     10     5362     New York     Red Bulls     RB     11     5363     San Jose     Earthquakes     SJ     50.1%     6
    7     5363     870988     2009050810     10     5362     New York     Red Bulls     RB     11     5363     San Jose     Earthquakes     SJ     49.9%     7
    8     5358     870961     2009041705     5     5358     D.C.     United     DC     9     5361     New England     Revolution     NE     44.6%     8
    9     5362     870984     2009050207     7     5360     Los Angeles     Galaxy     LA     10     5362     New York     Red Bulls     RB     44.4%     9
    10     5363     870983     2009050211     11     5363     San Jose     Earthquakes     SJ     17     5721     Chivas USA          Chv     44%     10
    11     5362     870945     2009040501     1     5354     Chicago     Fire     Chi     10     5362     New York     Red Bulls     RB     41.9%     11
    12     5359     870986     2009050606     6     5359     Kansas City     Wizards     KC     5     5358     D.C.     United     DC     30.5%     12What i'm trying to do is basically have the output formated so that when the team_id column matches the either the home_team_id or away_team_id colum i want the following columns to be renamed as:
    so if team_id = home_team_id for example then I want the following...
    sch.home_team_id_1032 as team_code_1032,
    sch.home_team_id as team_code,
    sch.home_team_name as team_name,
    sch.home_team_nickname as team_nickname,
    sch.home_team_abbrev as team_abbrev
    and then the away team columns would be...
    sch.away_team_id_1032 as opp_team_code_1032,
    sch.away_team_id as opp_team_code,
    sch.away_team_name as opp_team_name,
    sch.away_team_nickname as opp_team_nickname,
    sch.away_team_abbrev as opp_team_abbrev
    and same thing vice versa if the team_id column matches the away_team_idSorry, column names have to stay the same throughout the query. This is a very unusual request, and it's hard for me to imagine what you really want.
    You miight be able to do a UNION and add rows that look like column headings.
    No kidding, you have to post the results you want.
    No matter how clear an idea you have of what those resutls should be, no one else knows, and it's much easier to post the correct results than to accurately describe them.

  • How to use multiple statements inside the "THEN" block of CASE statement?

    Below is the code:
    SET @strTempString = case @strKeyMode
    WHEN 'AUTO/CYCLE'
    THEN  @strRefID + '|' + @strRetID
    WHEN 'CYCLE'
    THEN  @strRefID + '|' + @strRetID
    WHEN 'COMMERCIAL'
    THEN  @strRefID + '|' + @strRetID
    WHEN 'ISNAP'
    THEN  set @strFName = ltrim(rtrim((Left(dbo.CleanTheStringAdv(@strFName + '  ', 2) + '  ', 2))))
    '' + @strRefID + '|' + @strLName + '|' + @strFName + '|' + @strZIPorPolType
    WHEN 'ASNAP'
    THEN  @strRefID + '|' + @strRetID
    WHEN 'MOAT'
    THEN  @strRefID + '|' + @strRetID
    else '0'
    end 
    The first 3 conditions are understandable. How to use multiple statements in 4th case?
    Here I first want to set the value as:
    set @strFName = ltrim(rtrim((Left(dbo.CleanTheStringAdv(@strFName + '  ', 2) + '  ', 2))))
    and then return the string '' + @strRefID + '|' + @strLName + '|' + @strFName + '|' + @strZIPorPolType to @strTempString. 
    Please help me remove the syntax errors.
    Thanks in advance.

    Try below SQL
    DECLARE @strKeyMode varchar(20) = 'ISNAP'
    DECLARE @SQL VARCHAR(MAX)
    DECLARE @strRefID int=1
    DECLARE @strRetID INT=2
    --FIRST WAY
    IF @strKeyMode ='AUTO/CYCLE'
    SELECT CAST(@strRefID as varchar(10))
    ELSE IF @strKeyMode ='CYCLE'
    SELECT @sql = CAST(@strRefID as varchar(10)) + '|' + CAST(@strRetID as varchar(10))
    ELSE IF @strKeyMode='ISNAP'
    SELECT @sql = CAST(@strRefID as varchar(10)) + '|' + CAST(@strRetID as varchar(10))+'test'+'abc'
    ELSE
    SELECT @SQL='ABC'
    print @sql
    ----SECOND WAY
    SELECT @SQL = CASE @strKeyMode
    WHEN 'AUTO/CYCLE' THEN CAST(@strRefID as varchar(10))
    WHEN 'CYCLE' THEN CAST(@strRefID as varchar(10)) + '|' + CAST(@strRetID as varchar(10))
    WHEN 'ISNAP' THEN CAST(@strRefID as varchar(10)) + '|' + CAST(@strRetID as varchar(10))+'test'+'abc'
    ELSE 'No Record'
    END
    PRINT (@SQL)
    --Prashanth

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

  • Sql query slow due to case statement on Joins

    Hi
    The sql query runs very slow for 30 min when the below case statement is added on the joins. Could you please let me know how to tune it. if the case statement is not there then it runs only for 1 min.
    *( CASE*
    WHEN PO_DIST_GL_CODE_COMB.SEGMENT2 <> '1000'
    THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
    WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
    PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
    THEN DT_REQ_ALL.EMPMGMTCD
    END =DB2.DB2_FDW_MGMT_V.MH_CHILD  )
    SELECT  DISTINCT
      D.DB2_FDW_MGMT_V.RC_PARENT,
      DT_REQ_ALL.FULL_NAME,
      DT_REQ_ALL.EMP_COMPANY_CODE,
      DT_REQ_ALL.EMP_COST_CENTER,
      PO.PO_VENDORS.VENDOR_NAME,
      PO_PO_HEADERS_ALL2.SEGMENT1,
      PO_PO_HEADERS_ALL2.CREATION_DATE,
      PO_DIST_GL_CODE_COMB.SEGMENT1,
      PO_DIST_GL_CODE_COMB.SEGMENT2,
      PO_PO_HEADERS_ALL2.CURRENCY_CODE,
      PO_INV_DIST_ALL.INVOICE_NUM,
      PO_INV_DIST_ALL.INVOICE_DATE,
      (PO_INV_DIST_ALL.INVOICE_AMOUNT* PO_Rates_GL_DR.CONVERSION_RATE),
      (NVL(to_number(PO_DIST_ALL.AMOUNT_BILLED),0) * PO_Rates_GL_DR.CONVERSION_RATE),
      PO_LINES_LOC.LINE_NUM,
      GL.GL_SETS_OF_BOOKS.NAME,
      CASE
            WHEN TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE) > PO_INV_DIST_ALL.INVOICE_DATE
            THEN 1
            ELSE 0
        END ,
      PO.PO_REQUISITION_LINES_ALL.LINE_LOCATION_ID,
      TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE,'WW') + 8 WEEK_Ending
    FROM
      DB2.DB2_FDW_MGMT_V,
       PO.PO_VENDORS,
      PO.PO_HEADERS_ALL  PO_PO_HEADERS_ALL2,
      GL.GL_CODE_COMBINATIONS  PO_DIST_GL_CODE_COMB,
      AP.AP_INVOICES_ALL  PO_INV_DIST_ALL,
       PO.PO_DISTRIBUTIONS_ALL  PO_DIST_ALL,
      PO.PO_LINES_ALL  PO_LINES_LOC,
      GL.GL_SETS_OF_BOOKS,
      PO.PO_REQUISITION_LINES_ALL,
      PO.PO_LINE_LOCATIONS_ALL,
      AP.AP_INVOICE_DISTRIBUTIONS_ALL  PO_DIST_INV_DIST_ALL,
      APPS.HR_OPERATING_UNITS,
      PO.PO_REQ_DISTRIBUTIONS_ALL,
       SELECT DISTINCT
                            PO_RDA.DISTRIBUTION_ID,
                            PO_RLA.requisition_line_id,
                            PO_RHA.DESCRIPTION PO_Descr,
                            PO_RHA.NOTE_TO_AUTHORIZER PO_Justification,
                            Req_Emp.FULL_NAME,
                            GL_CC.SEGMENT1         Req_Company_Code,
                            GL_CC.SEGMENT2         Req_Cost_Center,
                            Req_Emp_CC.SEGMENT1    Emp_Company_Code,
                            Req_Emp_CC.SEGMENT2    Emp_Cost_Center,
                            (Case
                            When GL_CC.SEGMENT2 <> 8000
                            Then TRUNC(GL_CC.SEGMENT1) || TRUNC(GL_CC.SEGMENT2) || '_' || NVL(GL_CC.SEGMENT6,'000')
                            Else TRUNC(Req_Emp_CC.SEGMENT1) || TRUNC(Req_Emp_CC.SEGMENT2) || '_' || NVL(Req_Emp_CC.SEGMENT6,'000')
                            End) EmpMgmtCD
                FROM
                            PO.po_requisition_lines_all PO_rla,
                            PO.po_requisition_headers_all PO_rha,
                            PO.PO_REQ_DISTRIBUTIONS_ALL po_RDA,
                            GL.GL_CODE_COMBINATIONS gl_cc,
                            HR.PER_ALL_PEOPLE_F  Req_Emp,
                            HR.PER_ALL_ASSIGNMENTS_F Req_Emp_Assign,
                            HR.hr_all_organization_units Req_Emp_Org,
                            HR.pay_cost_allocation_keyflex Req_Emp_CC
                WHERE
                            PO_RDA.CODE_COMBINATION_ID = GL_CC.CODE_COMBINATION_ID and
                            PO_RLA.REQUISITION_LINE_ID = PO_RDA.REQUISITION_LINE_ID AND
                            PO_RLA.to_person_id = Req_Emp.PERSON_ID AND
                            PO_RLA.REQUISITION_HEADER_ID = PO_RHA.REQUISITION_HEADER_ID AND
                            (trunc(PO_rla.CREATION_DATE) between Req_Emp.effective_start_date and Req_Emp.effective_end_date OR
                            Req_Emp.effective_start_date IS NULL) AND
                            Req_Emp.PERSON_ID = Req_Emp_Assign.PERSON_ID AND
                            Req_Emp_Assign.organization_id = Req_Emp_Org.organization_id AND
                            (trunc(PO_rla.CREATION_DATE) between Req_Emp_Assign.effective_start_date and Req_Emp_Assign.effective_end_date OR
            Req_Emp_Assign.effective_start_date IS NULL) AND
            Req_Emp_Assign.primary_flag = 'Y' AND
            Req_Emp_Assign.assignment_type = 'E' AND
            Req_Emp_Org.cost_allocation_keyflex_id = Req_Emp_CC.cost_allocation_keyflex_id
      )  DT_REQ_ALL,
      SELECT
            FROM_CURRENCY,
            TO_CURRENCY,
            CONVERSION_DATE,
            CONVERSION_RATE
        FROM GL.GL_DAILY_RATES
        UNION
        SELECT Distinct
            'USD',
            'USD',
            CONVERSION_DATE,
            1
        FROM GL.GL_DAILY_RATES
      )  PO_Rates_GL_DR
    WHERE
      ( PO_DIST_GL_CODE_COMB.CODE_COMBINATION_ID=PO_DIST_ALL.CODE_COMBINATION_ID  )
      AND  ( PO_DIST_ALL.LINE_LOCATION_ID=PO.PO_LINE_LOCATIONS_ALL.LINE_LOCATION_ID  )
      AND  ( PO_PO_HEADERS_ALL2.VENDOR_ID=PO.PO_VENDORS.VENDOR_ID  )
      AND  ( PO_PO_HEADERS_ALL2.ORG_ID=APPS.HR_OPERATING_UNITS.ORGANIZATION_ID  )
      AND  ( GL.GL_SETS_OF_BOOKS.SET_OF_BOOKS_ID=APPS.HR_OPERATING_UNITS.SET_OF_BOOKS_ID  )
      AND  ( PO_PO_HEADERS_ALL2.CURRENCY_CODE=PO_Rates_GL_DR.FROM_CURRENCY  )
      AND  ( trunc(PO_PO_HEADERS_ALL2.CREATION_DATE)=PO_Rates_GL_DR.CONVERSION_DATE  )
      AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=PO.PO_REQ_DISTRIBUTIONS_ALL.DISTRIBUTION_ID(+)  )
      AND  ( PO.PO_REQ_DISTRIBUTIONS_ALL.REQUISITION_LINE_ID=PO.PO_REQUISITION_LINES_ALL.REQUISITION_LINE_ID(+)  )
      AND  ( PO_LINES_LOC.PO_HEADER_ID=PO_PO_HEADERS_ALL2.PO_HEADER_ID  )
      AND  ( PO.PO_LINE_LOCATIONS_ALL.PO_LINE_ID=PO_LINES_LOC.PO_LINE_ID  )
      AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=DT_REQ_ALL.DISTRIBUTION_ID(+)  )
      AND  ( PO_DIST_ALL.PO_DISTRIBUTION_ID=PO_DIST_INV_DIST_ALL.PO_DISTRIBUTION_ID(+)  )
      AND  ( PO_INV_DIST_ALL.INVOICE_ID(+)=PO_DIST_INV_DIST_ALL.INVOICE_ID  )
      AND  ( PO_INV_DIST_ALL.SOURCE(+) <> 'XML GATEWAY'   )
      AND 
       ( NVL(PO_PO_HEADERS_ALL2.CANCEL_FLAG,'N') <> 'Y'   )
       AND
       ( NVL(PO_PO_HEADERS_ALL2.CLOSED_CODE, 'OPEN') <> 'FINALLY CLOSED'  )
       AND
       ( NVL(PO_PO_HEADERS_ALL2.AUTHORIZATION_STATUS,'IN PROCESS') <> 'REJECTED'  )
       AND
       ( TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE)  BETWEEN TO_DATE('01-jan-2011') AND TO_DATE('04-jan-2011')  )
       AND
       PO_Rates_GL_DR.TO_CURRENCY  =  'USD'
         AND
       DB2.DB2_FDW_MGMT_V.RC_PARENT  In  ( 'Unavailable','Corp','Commercial'  )
       AND
      ( CASE
            WHEN PO_DIST_GL_CODE_COMB.SEGMENT2 <> '1000'
            THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
            WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
                    PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
            THEN DT_REQ_ALL.EMPMGMTCD     
        END =DB2.DB2_FDW_MGMT_V.MH_CHILD  )Explain plan. sorry can't get the explain plan from sql. this is from toad.
    Plan
    SELECT STATEMENT  ALL_ROWSCost: 53,932  Bytes: 2,607  Cardinality: 1                                                                                                                               
         79 HASH UNIQUE  Cost: 53,932  Bytes: 2,607  Cardinality: 1                                                                                                                          
              78 NESTED LOOPS OUTER  Cost: 53,931  Bytes: 2,607  Cardinality: 1                                                                                                                     
                   75 NESTED LOOPS OUTER  Cost: 53,928  Bytes: 2,560  Cardinality: 1                                                                                                                
                        72 NESTED LOOPS  Cost: 53,902  Bytes: 2,552  Cardinality: 1                                                                                                           
                             69 NESTED LOOPS OUTER  Cost: 53,900  Bytes: 2,533  Cardinality: 1                                                                                                      
                                  66 NESTED LOOPS OUTER  Cost: 53,898  Bytes: 2,521  Cardinality: 1                                                                                                 
                                       63 HASH JOIN OUTER  Cost: 53,896  Bytes: 2,509  Cardinality: 1                                                                                            
                                            40 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_DISTRIBUTIONS_ALL Cost: 3  Bytes: 26  Cardinality: 1                                                                                       
                                                 39 NESTED LOOPS  Cost: 17,076  Bytes: 2,400  Cardinality: 1                                                                                  
                                                      37 NESTED LOOPS  Cost: 17,073  Bytes: 2,374  Cardinality: 1                                                                             
                                                           34 NESTED LOOPS  Cost: 17,070  Bytes: 2,362  Cardinality: 1                                                                        
                                                                31 NESTED LOOPS  Cost: 17,066  Bytes: 2,347  Cardinality: 1                                                                   
                                                                     29 NESTED LOOPS  Cost: 17,066  Bytes: 2,339  Cardinality: 1                                                              
                                                                          26 NESTED LOOPS  Cost: 17,065  Bytes: 2,312  Cardinality: 1                                                         
                                                                               23 NESTED LOOPS  Cost: 17,064  Bytes: 2,287  Cardinality: 1                                                    
                                                                                    20 NESTED LOOPS  Cost: 17,062  Bytes: 2,261  Cardinality: 1                                               
                                                                                         17 NESTED LOOPS  Cost: 17,056  Bytes: 6,678  Cardinality: 3                                          
                                                                                              15 HASH JOIN  Cost: 17,056  Bytes: 6,663  Cardinality: 3                                     
                                                                                                   13 MERGE JOIN CARTESIAN  Cost: 135  Bytes: 30,352  Cardinality: 14                                
                                                                                                        5 VIEW VIEW DB2.DB2_FDW_MGMT_V Cost: 4  Bytes: 2,128  Cardinality: 1                           
                                                                                                             4 SORT UNIQUE  Cost: 4  Cardinality: 1                      
                                                                                                                  3 UNION-ALL                 
                                                                                                                       1 REMOTE REMOTE SERIAL_FROM_REMOTE PRDFDW.WORLD          
                                                                                                                       2 FAST DUAL  Cost: 3  Cardinality: 1            
                                                                                                        12 BUFFER SORT  Cost: 135  Bytes: 560  Cardinality: 14                           
                                                                                                             11 VIEW DB2. Cost: 131  Bytes: 560  Cardinality: 14                      
                                                                                                                  10 SORT UNIQUE  Cost: 131  Bytes: 310  Cardinality: 14                 
                                                                                                                       9 UNION-ALL            
                                                                                                                            7 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_DAILY_RATES Cost: 65  Bytes: 270  Cardinality: 9       
                                                                                                                                 6 INDEX SKIP SCAN INDEX (UNIQUE) GL.GL_DAILY_RATES_U1 Cost: 64  Cardinality: 1 
                                                                                                                            8 INDEX SKIP SCAN INDEX (UNIQUE) GL.GL_DAILY_RATES_U1 Cost: 64  Bytes: 4,368  Cardinality: 546       
                                                                                                   14 TABLE ACCESS FULL TABLE PO.PO_HEADERS_ALL Cost: 16,920  Bytes: 32,754  Cardinality: 618                                
                                                                                              16 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ORGANIZATION_UNITS_PK Cost: 0  Bytes: 5  Cardinality: 1                                     
                                                                                         19 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ORGANIZATION_INFORMATION Cost: 2  Bytes: 35  Cardinality: 1                                          
                                                                                              18 INDEX RANGE SCAN INDEX HR.HR_ORGANIZATION_INFORMATIO_FK2 Cost: 1  Cardinality: 2                                     
                                                                                    22 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ORGANIZATION_INFORMATION Cost: 2  Bytes: 26  Cardinality: 1                                               
                                                                                         21 INDEX RANGE SCAN INDEX HR.HR_ORGANIZATION_INFORMATIO_FK2 Cost: 1  Cardinality: 1                                          
                                                                               25 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_SETS_OF_BOOKS Cost: 1  Bytes: 25  Cardinality: 1                                                    
                                                                                    24 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_SETS_OF_BOOKS_U2 Cost: 0  Cardinality: 1                                               
                                                                          28 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_VENDORS Cost: 1  Bytes: 27  Cardinality: 1                                                         
                                                                               27 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_VENDORS_U1 Cost: 0  Cardinality: 1                                                    
                                                                     30 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ALL_ORGANIZATION_UNTS_TL_PK Cost: 0  Bytes: 8  Cardinality: 1                                                              
                                                                33 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_LINES_ALL Cost: 4  Bytes: 60  Cardinality: 4                                                                   
                                                                     32 INDEX RANGE SCAN INDEX (UNIQUE) PO.PO_LINES_U2 Cost: 2  Cardinality: 4                                                              
                                                           36 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_LINE_LOCATIONS_ALL Cost: 3  Bytes: 12  Cardinality: 1                                                                        
                                                                35 INDEX RANGE SCAN INDEX PO.PO_LINE_LOCATIONS_N1 Cost: 2  Cardinality: 1                                                                   
                                                      38 INDEX RANGE SCAN INDEX PO.PO_DISTRIBUTIONS_N1 Cost: 2  Cardinality: 1                                                                             
                                            62 VIEW DB2. Cost: 36,819  Bytes: 1,090  Cardinality: 10                                                                                       
                                                 61 HASH UNIQUE  Cost: 36,819  Bytes: 2,580  Cardinality: 10                                                                                  
                                                      60 NESTED LOOPS  Cost: 36,818  Bytes: 2,580  Cardinality: 10                                                                             
                                                           57 NESTED LOOPS  Cost: 36,798  Bytes: 2,390  Cardinality: 10                                                                        
                                                                54 NESTED LOOPS  Cost: 36,768  Bytes: 2,220  Cardinality: 10                                                                   
                                                                     51 NESTED LOOPS  Cost: 36,758  Bytes: 1,510  Cardinality: 10                                                              
                                                                          48 NESTED LOOPS  Cost: 36,747  Bytes: 1,050  Cardinality: 10                                                         
                                                                               45 HASH JOIN  Cost: 36,737  Bytes: 960  Cardinality: 10                                                    
                                                                                    43 HASH JOIN  Cost: 34,602  Bytes: 230,340  Cardinality: 3,490                                               
                                                                                         41 TABLE ACCESS FULL TABLE HR.PER_ALL_PEOPLE_F Cost: 1,284  Bytes: 1,848,420  Cardinality: 44,010                                          
                                                                                         42 TABLE ACCESS FULL TABLE PO.PO_REQUISITION_LINES_ALL Cost: 31,802  Bytes: 18,340,080  Cardinality: 764,170                                          
                                                                                    44 TABLE ACCESS FULL TABLE HR.PER_ALL_ASSIGNMENTS_F Cost: 2,134  Bytes: 822,540  Cardinality: 27,418                                               
                                                                               47 TABLE ACCESS BY INDEX ROWID TABLE HR.HR_ALL_ORGANIZATION_UNITS Cost: 1  Bytes: 9  Cardinality: 1                                                    
                                                                                    46 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.HR_ORGANIZATION_UNITS_PK Cost: 0  Cardinality: 1                                               
                                                                          50 TABLE ACCESS BY INDEX ROWID TABLE HR.PAY_COST_ALLOCATION_KEYFLEX Cost: 1  Bytes: 46  Cardinality: 1                                                         
                                                                               49 INDEX UNIQUE SCAN INDEX (UNIQUE) HR.PAY_COST_ALLOCATION_KEYFLE_PK Cost: 0  Cardinality: 1                                                    
                                                                     53 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQUISITION_HEADERS_ALL Cost: 1  Bytes: 71  Cardinality: 1                                                              
                                                                          52 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQUISITION_HEADERS_U1 Cost: 0  Cardinality: 1                                                         
                                                                56 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQ_DISTRIBUTIONS_ALL Cost: 3  Bytes: 17  Cardinality: 1                                                                   
                                                                     55 INDEX RANGE SCAN INDEX PO.PO_REQ_DISTRIBUTIONS_N1 Cost: 2  Cardinality: 1                                                              
                                                           59 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_CODE_COMBINATIONS Cost: 2  Bytes: 19  Cardinality: 1                                                                        
                                                                58 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_CODE_COMBINATIONS_U1 Cost: 1  Cardinality: 1                                                                   
                                       65 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQ_DISTRIBUTIONS_ALL Cost: 2  Bytes: 12  Cardinality: 1                                                                                            
                                            64 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQ_DISTRIBUTIONS_U1 Cost: 1  Cardinality: 1                                                                                       
                                  68 TABLE ACCESS BY INDEX ROWID TABLE PO.PO_REQUISITION_LINES_ALL Cost: 2  Bytes: 12  Cardinality: 1                                                                                                 
                                       67 INDEX UNIQUE SCAN INDEX (UNIQUE) PO.PO_REQUISITION_LINES_U1 Cost: 1  Cardinality: 1                                                                                            
                             71 TABLE ACCESS BY INDEX ROWID TABLE GL.GL_CODE_COMBINATIONS Cost: 2  Bytes: 19  Cardinality: 1                                                                                                      
                                  70 INDEX UNIQUE SCAN INDEX (UNIQUE) GL.GL_CODE_COMBINATIONS_U1 Cost: 1  Cardinality: 1                                                                                                 
                        74 TABLE ACCESS BY INDEX ROWID TABLE AP.AP_INVOICE_DISTRIBUTIONS_ALL Cost: 26  Bytes: 16  Cardinality: 2                                                                                                           
                             73 INDEX RANGE SCAN INDEX AP.AP_INVOICE_DISTRIBUTIONS_N7 Cost: 2  Cardinality: 37                                                                                                      
                   77 TABLE ACCESS BY INDEX ROWID TABLE AP.AP_INVOICES_ALL Cost: 3  Bytes: 47  Cardinality: 1                                                                                                                
                        76 INDEX RANGE SCAN INDEX (UNIQUE) AP.AP_INVOICES_U1 Cost: 2  Cardinality: 1                                                                                                           Thanks

    Forming a new table "new_table" with 3 tables which particiapate in CASE statement logic.
    with  DT_REQ_ALL  as
       SELECT DISTINCT
                            PO_RDA.DISTRIBUTION_ID,
                            PO_RLA.requisition_line_id,
                            PO_RHA.DESCRIPTION PO_Descr,
                            PO_RHA.NOTE_TO_AUTHORIZER PO_Justification,
                            Req_Emp.FULL_NAME,
                            GL_CC.SEGMENT1         Req_Company_Code,
                            GL_CC.SEGMENT2         Req_Cost_Center,
                            Req_Emp_CC.SEGMENT1    Emp_Company_Code,
                            Req_Emp_CC.SEGMENT2    Emp_Cost_Center,
                            (Case
                            When GL_CC.SEGMENT2  8000
                            Then TRUNC(GL_CC.SEGMENT1) || TRUNC(GL_CC.SEGMENT2) || '_' || NVL(GL_CC.SEGMENT6,'000')
                            Else TRUNC(Req_Emp_CC.SEGMENT1) || TRUNC(Req_Emp_CC.SEGMENT2) || '_' || NVL(Req_Emp_CC.SEGMENT6,'000')
                            End) EmpMgmtCD
                FROM
                            PO.po_requisition_lines_all PO_rla,
                            PO.po_requisition_headers_all PO_rha,
                            PO.PO_REQ_DISTRIBUTIONS_ALL po_RDA,
                            GL.GL_CODE_COMBINATIONS gl_cc,
                            HR.PER_ALL_PEOPLE_F  Req_Emp,
                            HR.PER_ALL_ASSIGNMENTS_F Req_Emp_Assign,
                            HR.hr_all_organization_units Req_Emp_Org,
                            HR.pay_cost_allocation_keyflex Req_Emp_CC
                WHERE
                            PO_RDA.CODE_COMBINATION_ID = GL_CC.CODE_COMBINATION_ID and
                            PO_RLA.REQUISITION_LINE_ID = PO_RDA.REQUISITION_LINE_ID AND
                            PO_RLA.to_person_id = Req_Emp.PERSON_ID AND
                            PO_RLA.REQUISITION_HEADER_ID = PO_RHA.REQUISITION_HEADER_ID AND
                            (trunc(PO_rla.CREATION_DATE) between Req_Emp.effective_start_date and Req_Emp.effective_end_date OR
                            Req_Emp.effective_start_date IS NULL) AND
                            Req_Emp.PERSON_ID = Req_Emp_Assign.PERSON_ID AND
                            Req_Emp_Assign.organization_id = Req_Emp_Org.organization_id AND
                            (trunc(PO_rla.CREATION_DATE) between Req_Emp_Assign.effective_start_date and Req_Emp_Assign.effective_end_date OR
            Req_Emp_Assign.effective_start_date IS NULL) AND
            Req_Emp_Assign.primary_flag = 'Y' AND
            Req_Emp_Assign.assignment_type = 'E' AND
            Req_Emp_Org.cost_allocation_keyflex_id = Req_Emp_CC.cost_allocation_keyflex_id
    SELECT  DISTINCT
      D.DB2_FDW_MGMT_V.RC_PARENT,
      DT_REQ_ALL.FULL_NAME,
      DT_REQ_ALL.EMP_COMPANY_CODE,
      DT_REQ_ALL.EMP_COST_CENTER,
      PO.PO_VENDORS.VENDOR_NAME,
      PO_PO_HEADERS_ALL2.SEGMENT1,
      PO_PO_HEADERS_ALL2.CREATION_DATE,
      PO_DIST_GL_CODE_COMB.SEGMENT1,
      PO_DIST_GL_CODE_COMB.SEGMENT2,
      PO_PO_HEADERS_ALL2.CURRENCY_CODE,
      PO_INV_DIST_ALL.INVOICE_NUM,
      PO_INV_DIST_ALL.INVOICE_DATE,
      (PO_INV_DIST_ALL.INVOICE_AMOUNT* PO_Rates_GL_DR.CONVERSION_RATE),
      (NVL(to_number(PO_DIST_ALL.AMOUNT_BILLED),0) * PO_Rates_GL_DR.CONVERSION_RATE),
      PO_LINES_LOC.LINE_NUM,
      GL.GL_SETS_OF_BOOKS.NAME,
      CASE
            WHEN TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE) > PO_INV_DIST_ALL.INVOICE_DATE
            THEN 1
            ELSE 0
        END ,
      PO.PO_REQUISITION_LINES_ALL.LINE_LOCATION_ID,
      TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE,'WW') + 8 WEEK_Ending
    FROM
      ( SELECT * FROM
          DB2.DB2_FDW_MGMT_V,
          GL.GL_CODE_COMBINATIONS  PO_DIST_GL_CODE_COMB,
          DT_REQ_ALL
        WHERE
              DB2.DB2_FDW_MGMT_V.RC_PARENT  In  ( 'Unavailable','Corp','Commercial'  )
           AND
            CASE
               WHEN PO_DIST_GL_CODE_COMB.SEGMENT2  <>  '1000'
               THEN  PO_DIST_GL_CODE_COMB.SEGMENT1 || PO_DIST_GL_CODE_COMB.SEGMENT2 || '_' || NVL(PO_DIST_GL_CODE_COMB.SEGMENT6,'000')
               WHEN DT_REQ_ALL.EMPMGMTCD IS NOT NULL AND
                    PO_DIST_GL_CODE_COMB.SEGMENT2 = '1000'
               THEN DT_REQ_ALL.EMPMGMTCD     
            END =DB2.DB2_FDW_MGMT_V.MH_CHILD
       )   new_table,
       PO.PO_VENDORS,
      PO.PO_HEADERS_ALL  PO_PO_HEADERS_ALL2,
      AP.AP_INVOICES_ALL  PO_INV_DIST_ALL,
       PO.PO_DISTRIBUTIONS_ALL  PO_DIST_ALL,
      PO.PO_LINES_ALL  PO_LINES_LOC,
      GL.GL_SETS_OF_BOOKS,
      PO.PO_REQUISITION_LINES_ALL,
      PO.PO_LINE_LOCATIONS_ALL,
      AP.AP_INVOICE_DISTRIBUTIONS_ALL  PO_DIST_INV_DIST_ALL,
      APPS.HR_OPERATING_UNITS,
      PO.PO_REQ_DISTRIBUTIONS_ALL,
      SELECT
            FROM_CURRENCY,
            TO_CURRENCY,
            CONVERSION_DATE,
            CONVERSION_RATE
        FROM GL.GL_DAILY_RATES
        UNION
        SELECT Distinct
            'USD',
            'USD',
            CONVERSION_DATE,
            1
        FROM GL.GL_DAILY_RATES
      )  PO_Rates_GL_DR
    WHERE
      ( PO_DIST_GL_CODE_COMB.CODE_COMBINATION_ID=PO_DIST_ALL.CODE_COMBINATION_ID  )
      AND  ( PO_DIST_ALL.LINE_LOCATION_ID=PO.PO_LINE_LOCATIONS_ALL.LINE_LOCATION_ID  )
      AND  ( PO_PO_HEADERS_ALL2.VENDOR_ID=PO.PO_VENDORS.VENDOR_ID  )
      AND  ( PO_PO_HEADERS_ALL2.ORG_ID=APPS.HR_OPERATING_UNITS.ORGANIZATION_ID  )
      AND  ( GL.GL_SETS_OF_BOOKS.SET_OF_BOOKS_ID=APPS.HR_OPERATING_UNITS.SET_OF_BOOKS_ID  )
      AND  ( PO_PO_HEADERS_ALL2.CURRENCY_CODE=PO_Rates_GL_DR.FROM_CURRENCY  )
      AND  ( trunc(PO_PO_HEADERS_ALL2.CREATION_DATE)=PO_Rates_GL_DR.CONVERSION_DATE  )
      AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=PO.PO_REQ_DISTRIBUTIONS_ALL.DISTRIBUTION_ID(+)  )
      AND  ( PO.PO_REQ_DISTRIBUTIONS_ALL.REQUISITION_LINE_ID=PO.PO_REQUISITION_LINES_ALL.REQUISITION_LINE_ID(+)  )
      AND  ( PO_LINES_LOC.PO_HEADER_ID=PO_PO_HEADERS_ALL2.PO_HEADER_ID  )
      AND  ( PO.PO_LINE_LOCATIONS_ALL.PO_LINE_ID=PO_LINES_LOC.PO_LINE_ID  )
      AND  ( PO_DIST_ALL.REQ_DISTRIBUTION_ID=DT_REQ_ALL.DISTRIBUTION_ID(+)  )
      AND  ( PO_DIST_ALL.PO_DISTRIBUTION_ID=PO_DIST_INV_DIST_ALL.PO_DISTRIBUTION_ID(+)  )
      AND  ( PO_INV_DIST_ALL.INVOICE_ID(+)=PO_DIST_INV_DIST_ALL.INVOICE_ID  )
      AND  ( PO_INV_DIST_ALL.SOURCE(+)  'XML GATEWAY'   )
      AND 
       ( NVL(PO_PO_HEADERS_ALL2.CANCEL_FLAG,'N')  'Y'   )
       AND
       ( NVL(PO_PO_HEADERS_ALL2.CLOSED_CODE, 'OPEN')  'FINALLY CLOSED'  )
       AND
       ( NVL(PO_PO_HEADERS_ALL2.AUTHORIZATION_STATUS,'IN PROCESS')  'REJECTED'  )
       AND
       ( TRUNC(PO_PO_HEADERS_ALL2.CREATION_DATE)  BETWEEN TO_DATE('01-jan-2011') AND TO_DATE('04-jan-2011')  )
       AND
       PO_Rates_GL_DR.TO_CURRENCY  =  'USD'
      

  • SQL query problem - select max (case... aggregate function)

    Hi,
    I have a problem with below sql query, it gives me problem/error message 'ORA-00937: not a single-group group function', why?
    select sag.afdeling, sag.sagsnr, to_char(sag.start_dato, 'yyyy-mm-dd'), sag.stat, BOGF_TRANS.TRANSTYPE,
    max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
    max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
    max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
    from sag
    join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
    where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
    group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
    If I exclude (columns) as below it give me correct summations (max (case... sum(...)) but then I miss some important info that I need
    select
    max (case when BOGF_TRANS.TRANSTYPE = 'K' then sum(bogf_trans.belobdkk) end) + -- as "TRANSTYPE K",
    max (case when BOGF_TRANS.TRANSTYPE = 'D' then sum(bogf_trans.belobdkk) end) as "TRANSTYPE K & D",
    max (case when BOGF_TRANS.TRANSTYPE = 'S' then sum(bogf_trans.belobdkk) end) as "SUM TRANSTYPE S"
    from sag
    join bogf_trans on sag.selskab = bogf_trans.selskab and sag.sagsnr = bogf_trans.sagsnr and sag.afdeling = bogf_trans.afdeling
    where SAG.SELSKAB=37 and SAG.AFDELING = 'SUS' AND SAG.SAGSNR = 10876
    group by sag.afdeling, sag.sagsnr, sag.start_dato, sag.stat, BOGF_TRANS.TRANSTYPE
    Any ideas?

    Moved to more sutable forum, sorry.

  • LIKE statement in CASE statement

    Hi,
    I have a table called amounttagged as below
    Amount Tag
    10000 ABDCBD
    20000 CBDADE
    30000 CBDABD
    40000 ABDADE
    and my sql statement is as below,
    select Amount, case when tag like '%ABD%' then 'ABD' else when tag like '%CBD%' then 'CBD' else 'ADE' end as tag
    from amounttagged
    The problem is when the tag is ABDCBD it will only be displayed for 'tag like '%ABD%' statement and the tag is only ABD. How can I make it to appear for both tag ABD and CBD?
    Pls see example of result of sql
    Amount Tag
    10000 ABD
    20000 CBD
    30000 CBD
    40000 ADE
    How can I make the amount 10000 appear for tag CBD as well? Pls advise.

    I just tested mine, and I missed off a couple of commas...
    SQL> ed
    Wrote file afiedt.buf
      1  with t as (select 10000 as amount, 'ABDCBD' as tag from dual union all
      2             select 20000, 'CBDADE' from dual union all
      3             select 30000, 'CBDABD' from dual union all
      4             select 40000, 'ABDADE' from dual)
      5  --
      6  -- end of test data
      7  --
      8  select Amount, decode(rn,1,abd,2,cbd,ade) as tag
      9  from (
    10        select Amount,
    11               case when tag like '%ABD%' then 'ABD' else null end as abd,
    12               case when tag like '%CBD%' then 'CBD' else null end as cbd,
    13               case when tag not like '%ABD%' and tag not like '%CBD%' then 'ADE' else null end as ade
    14        from t /* amounttagged */
    15       )
    16      ,(select rownum rn from dual connect by rownum <= 3)
    17  where decode(rn,1,abd,2,cbd,ade) is not null
    18* order by amount, tag
    SQL> /
        AMOUNT TAG
         10000 ABD
         10000 CBD
         20000 CBD
         30000 ABD
         30000 CBD
         40000 ABD
    6 rows selected.
    SQL>

  • Why doesn't this case statement work?

    SELECT
    case when PRODUCTS.PRODUCT_NAME in
    select case when rank() over(order by ( sum(ag.RX_CNT) ) desc) < 6 then ( p.PRODUCT_NAME ) else 'XXXX' END RankedProduct
    FROM
    PAP_MONTHLYTIME_DIM m,
    PAP_PRESCRIPTIONS_DEMOG_AGG ag,
    PRODUCTS p,
    PAP_ENROLLMENT_FLAGS_DIM f
    WHERE
    ( m.MONTHLYTIME_DIM_ID = ag.MONTHLYTIME_DIM_ID )
    AND ( ag.ENROLLMENT_FLAGS_DIM_ID = f.ENROLLMENT_FLAGS_DIM_ID )
    AND ( p.PRODUCT_ID = ag.PRODUCT_DIM_ID )
    AND ( f.ACTIVE_FLAG = 'Y' )
    AND m.CALENDAR_YEAR_MONTH = '2007-04'
    GROUP BY
    m.MONTH_END_DATE,
    p.PRODUCT_NAME
    then
    ( PRODUCTS.PRODUCT_NAME ) else 'All Other' end as ProdNm,
    PRODUCTS.PRODUCT_NAME,
    sum(PAP_PRESCRIPTIONS_DEMOG_AGG.RX_CNT)
    FROM
    PRODUCTS,
    PAP_PRESCRIPTIONS_DEMOG_AGG
    WHERE
    ( PRODUCTS.PRODUCT_ID=PAP_PRESCRIPTIONS_DEMOG_AGG.PRODUCT_DIM_ID )
    GROUP BY
    PRODUCTS.PRODUCT_NAME
    The first case statement is not working properly. First off - I know I can do this without the subquery in the case statement, but it's then tied to the Month and I don't want that.
    The result set of the subquery contains valid product_names that match EXACTLY (I added LTRIM RTRIM just in case), but the ProdNm field still evaluates to "All Other" for them. If I change the subquery to something basic and remove the rank function, it works, but of course I need that function. My understanding is that it shouldn't matter what function is in the subquery. I thought Oracle would get the result set of the subquery first, then evaluate the case statement based on the result set (the subquery is obviously not correlated).
    Any ideas?
    Thanks.

    My understanding is that it shouldn't matter what function is in the subquery. I thought Oracle would get the result set of the subquery first, then evaluate the case statement based on the result set (the subquery is obviously not correlated). It looks like the queries ARE somehow correlated. Consider the two simplified queries:
    michaels>  SELECT   ename, deptno,
             CASE
                WHEN deptno IN (
                       SELECT CASE
                                 WHEN ROW_NUMBER () OVER (ORDER BY NULL) < 3
                                    THEN deptno
                                 ELSE 1000
                              END
                         FROM dept)
                   THEN 'Found'
                ELSE 'NOT Found'
             END FOUND
        FROM emp
    ORDER BY deptno
    ENAME          DEPTNO FOUND   
    CLARK              10 NOT Found
    KING               10 NOT Found
    MILLER             10 NOT Found
    JONES              20 NOT Found
    FORD               20 NOT Found
    ADAMS              20 NOT Found
    SMITH              20 NOT Found
    SCOTT              20 NOT Found
    WARD               30 NOT Found
    TURNER             30 NOT Found
    ALLEN              30 NOT Found
    JAMES              30 NOT Found
    BLAKE              30 NOT Found
    MARTIN             30 NOT Found
    michaels>  SELECT   ename, deptno,
             CASE
                WHEN deptno IN (
                       SELECT *
                         FROM (SELECT CASE
                                         WHEN ROW_NUMBER () OVER (ORDER BY NULL) < 3
                                            THEN deptno
                                         ELSE 1000
                                      END
                                 FROM dept))
                   THEN 'Found'
                ELSE 'NOT Found'
             END FOUND
        FROM emp
    ORDER BY deptno
    ENAME          DEPTNO FOUND   
    CLARK              10 Found   
    KING               10 Found   
    MILLER             10 Found   
    JONES              20 Found   
    FORD               20 Found   
    ADAMS              20 Found   
    SMITH              20 Found   
    SCOTT              20 Found   
    WARD               30 NOT Found
    TURNER             30 NOT Found
    ALLEN              30 NOT Found
    JAMES              30 NOT Found
    BLAKE              30 NOT Found
    MARTIN             30 NOT FoundSo in the first query ROW_NUMBER() evaluates to NULL (not sure why) so the condition will never be satisfied! This is easily proofed when actually testing for nullity:
    WHEN ROWNUM() OVER (ORDER BY NULL) IS NULL THEN
    ...will always show 'Found'!
    Inlining the subquery »materializes« it, and ROW_NUMBER() gets the desired value.

  • Help: Case statement Error

    Hello Folks,
    Am trying to execute a procedure but somehow its returning an error near the case statement.I am thinking whether i have written it correctly or not. Can anyone please advice.Am just posting that specific part of the code where it points. Thanks a million.
    select  @v_retained_by_client = case c.code when '50' then RETAINED_BY_CLIENT  -- Its pointing the error at this line
                                                  when '51' then RETAINED_BY_CLIENT                
                                                  when '52' then RETAINED_BY_CLIENT
                                                  else 0
                                                  end,
               @v_hriretainedfee = case c.code  when '50' then hri_fee     
                                                when  '51' then hri_fee
                                                when '52' then hri_fee
                                                else 0
                                                end,
              @v_adminretainedfee = case c.code when '50' then admin_fee    
                                                when  '51' then admin_fee
                                                when '52' then admin_fee
                                                else 0
                                               end,  
               @v_allocation_amt = case c.code       when '50' then ALLOCATION_CHECK_AMOUNT
                                                        when '51' then ALLOCATION_CHECK_AMOUNT
                                                       when '52' then ALLOCATION_CHECK_AMOUNT          
                                                 else 0
                                              end,
              @v_cur_recoveryrefund = case c.code when '96' then sum(recovery_amount)      
              end,
              @v_cur_recoveryvoid = case c.code when '95'  then sum(recovery_amount)   
              end,
              @v_cur_hrirefund = case c.code when '96' then sum(hri_fee)            
              end,
              @v_cur_hrivoid = case c.code when '95'  then sum(hri_fee)             
              end,
                @v_cur_adminrefund = case c.code when '96' then sum(admin_fee)            
              end,
              @v_cur_adminvoid = case c.code when '95'  then sum(admin_fee)              
              end,
                @v_cur_taxrefund = case c.code when '96' then sum(taxes)             
              end,
              @v_cur_taxvoid = case c.code when '95' then sum(taxes)              
              end
                 from cash_receipt b, recovery_type c
                 where case_id = @v_case_id
              and b.recovery_type_id = c.recovery_type_id
              and recovery_date between @p_startdate and @p_enddate
            end         Edited by: user11961230 on Nov 25, 2009 1:27 PM

    Hi,
    Sorry, I don't know anything about SQL Server.
    I do know you should take baby steps, especially when trying something you're not sure how to do.
    Get rid of all but one CASE expression, until you know how to make that one work.
    When you do get that to work, add one more, as much like the first as possible, to make sure you know how to do two columns in the same query.
    Get asomething working, then try adding a little bit to it. When you do have errors, you'll have a much better idea what caused the errror.
    It's suspicious that you're using aggregate functions in some places, like this
    @v_cur_recoveryrefund = case c.code when '96' then sum(recovery_amount)      
              end,but not in the first CASE expressions. You might try <tt>MAX (CASE case c.code when '50' then ... END)</tt>
    I also find it odd that you're using <tt>CASE ... SUM (...)</tt> ; in Oracle, that would be very rare. It implies that the same expression will be in the GROUP BY clause.
    It's more common to have <tt>SUM (CASE ... END)</tt> , like this:
    SUM ( CASE c.code WHEN '96' THEN recovery_amount END )

  • SQL Query - case statement

    HI Friends ,
    My Scenario in table data :
    EmpId       fromdate           todate                Billtype
    2              01-09-2014        09-09-2014         B
    3              01-09-2014         NULL                   B
    2              10-09-2014        NULL                    P
    4             01-09-2014        NULL                     U
    5             01-09-2014        15-09-2014           B
    5             16-09-2014        30-09-2014            U
    OutPut :
    EmpId    Status
    2     P
    3     B
    4    U
    5    P
    requirement : Need to develop this Sql Query ..Using the Case statement .
    Please Help
    thanks
    Rakesh

    Wonderfull Patrick......
    I executed the logic and returning the expected result .  Thanks a lot.
    But still need some more modification ......
    suppose an employee E7 has the following entry :
    E7    01-04-2014      20-06-2014       B
    E7    21-06-2014      Null                   P
    This means that the Employee E7 has Joined Project P1 in April First  on a Billed Project and worked till July 20th and then again Moved to a Partial Billing Project P3 and from that July Till working in that Project
    So as per logic , we are suppose to get the Status of the Employees in the previous Month.....logically means October......  so for the same E7  the Status would  be "P"...because from July he is working on a Partial Billed Project
    .....   If suppose E7 worked on an Unbilled Project from July .... then for the month of October ......the Status for the same  E7 would be "U"
    Soooo ......if Employee E8 made 2 transitions within a month take example of last month October .
    E7    01-04-2014      20-06-2014        B
    E7    21-06-2014      Null                    P
    E8    01-10-2014      20-10-2014       B
    E8    21-10-2014      23-10-2014       P
    E8    24-10-2014      Null/Empty         U
    so for this employee the Result for the November month will be  "P" but if i check in month of december ...... for the same the satus should be "U" because from the last October 24th he is working on a "UnBilled Project"
    Please Help ......!!!
    I think what you need is just a filter like below
    declare @FromDate datetime
    SET @FromDate ='20141001'
    SELECT EmpId,
    CASE WHEN MAX(Billtype) = 'B' THEN 'B'
    WHEN MIN(Billtype) = 'U' THEN 'U'
    ELSE 'P'
    END AS Status
    FROM table
    WHERE fromdate >= @FromDate
    OR (fromdate < @Fromdate
    AND (todate > @FromDate
    OR todate IS NULL))
    GROUP BY EmpId
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • 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

  • Case statement doubt

    Hi,
    I need some help with a simple case statement. lets say i have a table called name which has following 2 rows -
    ID first_name last_name
    1 JOHN SMITH
    2 JOHN
    i want to write a statement like :-
    select id,case when first_name like '%JO%' then 'John in first_name'
    when last_name like '%SM%' then 'Smith in last_name'
    end result from sample_table;
    The result displayed is -
    1 John in first_name
    2 John in first_name
    how can i rewrite this query to also include a 3rd row which will display the result as -
    1 John in first_name
    2 John in first_name
    1 Smith in last_name
    I want to display this 3rd row which displays last name also.
    Please help.

    974647 wrote:
    Hi,
    I need some help with a simple case statement. lets say i have a table called name which has following 2 rows -
    ID first_name last_name
    1 JOHN SMITH
    2 JOHN
    i want to write a statement like :-
    select id,case when first_name like '%JO%' then 'John in first_name'
    when last_name like '%SM%' then 'Smith in last_name'
    end result from sample_table;
    The result displayed is -
    1 John in first_name
    2 John in first_name
    how can i rewrite this query to also include a 3rd row which will display the result as -
    1 John in first_name
    2 John in first_name
    1 Smith in last_name
    I want to display this 3rd row which displays last name also.
    Please help.Hi,
    welcome to the forum.
    Please read SQL and PL/SQL FAQ
    Additionally when you put some code please enclose it between two lines starting with {noformat}{noformat}
    i.e.:
    {noformat}{noformat}
    SELECT ...
    {noformat}{noformat}
    What you want to achieve cannot be done with a single query without using some tricks.
    Let's start from the point that your table has 2 rows. If you make a query without using a filter (A WHERE clause) and without using any CONNECT BY clause the number of rows returned by your query will be 2.
    So a possible solution is to make a union of the same table applying the condition to select only records that you want to display.
    i.e.:
    First I select only records having first_name like '%JO%' then I make a union with all rows having last_name like '%SM%'WITH sample_table AS
    SELECT 1 id, 'JOHN' first_name, 'SMITH' last_name FROM DUAL UNION ALL
    SELECT 2 id, 'JOHN' first_name, NULL last_name FROM DUAL
    SELECT id, 'John in first_name' txt
    FROM sample_table
    WHERE first_name like '%JO%'
    UNION ALL
    SELECT id, 'Smith in last_name' txt
    FROM sample_table
    WHERE last_name like '%SM%';
    ID TXT
    1 John in first_name
    2 John in first_name
    1 Smith in last_name
    Regards.
    Al
    Edited by: Alberto Faenza on Dec 3, 2012 5:27 PM
    Removed case, no need                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Doubt in case statement  in sql

    hiii guruz
    i am writing a code in HR schema for case its like this it works fine as i want it to
    select commission_pct ,
    case
    when commission_pct is null
    then 'null'
    else 'not null' end "comm"
    from employees
    but when i write+
    select commission_pct ,
    case commission_pct
    when null then 'null'
    else 'its not null'
    end "chk"
    from employees
    the o/p that i get is only in every field
    its not null
    why is it not showing
    *'null'*
    as it was supposed to show it
    thks

    oracle 10g
    using sql *plus                                                                                                                                                                                                                                   

  • Trying to use greater than in a case statement

    What is the correct way to write this case statement?
    Case
    F.NextOrder2
    > F.CutOff
    Then
    Else F.NextOrder2
    as NextOrder3

    You're missing END, e.g.
    CASE when F.NextOrder2 > F.CutOff then '' else cast(F.NextOrder2 as varchar(100)) end as NextOrder3
    All values in the CASE statement must be of the same data type.
    See this blog post why
    SQL Server Case/When Data Type problems
    Premature optimization is the root of all evil in programming. (c) by Donald Knuth
    Naomi Nosonovsky, Sr. Programmer-Analyst
    My blog

  • SQL Case statement Help....

    Hi , I have to Compare two columns to see if they are matching or not....and give the count() of overrides if they are not matching/
    I have got that with the below SQL:
    Count of Overrides =
    select count(Case when Col_1 != Col_2 then 1 else null end) Overrides
    from table_1, table_2
    where table_1.id = table_2.id
    But now i have to look at two columns and get the count()
    I have
    col_1 and col_2 in table_1 and
    col_3 and col_4 in table_2
    (I have to compare col_1 with col_2 and...... col_3 with col_4 and if either of them is not matching.... count it as an override
    Will the following SQL return correct values?
    Count of Overrides =
    Select
    Count( Case when (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end) Overrides
    from table_1, table_2
    where table_1.id = table_2.id
    Thanks

    "yes, it can be rewritten as a decode. but why bother?"
    Well, although I do like Sy's code better, the decode version does naturally handle NULLs unlike the case.
    SQL> WITH t AS (
      2     SELECT 1 col_1, 1 col_2, 2 col_3, 2 col_4 FROM dual UNION ALL
      3     SELECT 1, 1, 2, 3 FROM dual UNION ALL
      4     SELECT 1, 2, 3, 3 FROM dual UNION ALL
      5     SELECT null, 1, 2, 2 FROM dual UNION ALL
      6     SELECT 1, 1, 2, null FROM dual UNION ALL
      7     SELECT 1, 2, 3, 4 FROM dual)
      8  SELECT col_1, col_2, col_3, col_4,
      9         CASE WHEN (col_1 ! = col_2) or (col_3 != col_4) then 1 else null end Ocase,
    10         DECODE(col_1, col_2, DECODE(col_3, col_4, NULL, 1), 1) odecode
    11  FROM t;
         COL_1      COL_2      COL_3      COL_4      OCASE O
             1          1          2          2
             1          1          2          3          1 1
             1          2          3          3          1 1
                        1          2          2            1
             1          1          2                       1
             1          2          3          4          1 1John

Maybe you are looking for