Case or if condition in sql

I need to load distinct enames to target table emp.
1st condition: check the latest mod_time of ename whether active or inactive status
2nd condition: if last mod time is same for one ename check emp_status='ACTIVE' load active record
3rd condition if the ACTIVE records are more than on take max(emp_id)
Emp source table
emp_id  ename mod_date         emp_status    
103     MARY     22-JAN-2012       INACTIVE
104     MARY      21-JAN-2012      ACTIVE
100          john    21-JAN-2012        ACTIVE
101          john    21-JAN-2012       INACTIVE
102          john    21-JAN-2012        ACTIVE
105     JUHI     21-JAN-2012       INACTIVE
106     JUHI      21-JAN-2012      ACTIVE
107     CHEN     21-JAN-2012       INACTIVE
108     CHEN      22-JAN-2012      ACTIVE
109     james     21-JAN-2012       INACTIVE
110     james      22-JAN-2012      INACTIVE
EXPECTED OUTPUT emp target
emp_id  ename mod_date         emp_status    
103     MARY     22-JAN-2012       INACTIVE --take latest mod_time  first priority check.
102          john    21-JAN-2012        ACTIVE --first check latest mod_time. since two active records with the same mod_time then take max(emp_id)
106     JUHI      21-JAN-2012      ACTIVE  --two records with same mod_time with status active and inactive. take active record.
108     CHEN      22-JAN-2012      ACTIVE --active is the latest mod time
110     james      22-JAN-2012      INACTIVE --  two records with same mod_time with status active take max(emp_id)---------------------------
how can i implement this logic with one sql command and insert into emp_target table
I should have only one record per employee from source
Edited by: choti on Feb 21, 2013 4:58 PM

Not sure that this is the most elegant way to do this, but...
WITH emp AS
  SELECT 103 emp_id, 'MARY' ename, '22-JAN-2012' mod_date, 'INACTIVE' emp_status FROM dual UNION ALL
  SELECT 104, 'MARY', '21-JAN-2012', 'ACTIVE' FROM dual UNION ALL
  SELECT 100, 'john', '21-JAN-2012', 'ACTIVE' FROM dual UNION ALL
  SELECT 101, 'john', '21-JAN-2012', 'INACTIVE' FROM dual UNION ALL
  SELECT 102, 'john', '21-JAN-2012', 'ACTIVE' FROM dual UNION ALL
  SELECT 105, 'JUHI', '21-JAN-2012', 'INACTIVE' FROM dual UNION ALL
  SELECT 106, 'JUHI', '21-JAN-2012', 'ACTIVE' FROM dual UNION ALL
  SELECT 107, 'CHEN', '21-JAN-2012', 'INACTIVE' FROM dual UNION ALL
  SELECT 108, 'CHEN', '22-JAN-2012', 'ACTIVE' FROM dual UNION ALL
  SELECT 109, 'james','21-JAN-2012', 'INACTIVE' FROM dual UNION ALL
  SELECT 110, 'james','22-JAN-2012', 'INACTIVE' FROM dual
emp1 AS (
  SELECT emp_id, ename, mod_date, emp_status, MAX(mod_date) OVER (PARTITION BY ename) max_mod_date
    FROM emp
emp2 AS (
  SELECT emp_id, ename, mod_date, emp_status, MIN(emp_status) OVER (PARTITION BY ename, mod_date) min_emp_status
    FROM emp1
    WHERE mod_date = max_mod_date
emp3 AS (
SELECT emp_id, ename, mod_date, emp_status, MAX(emp_id) OVER (PARTITION BY ename, mod_date, emp_status) max_emp_id
  FROM emp2
  WHERE min_emp_status = emp_status
emp4 AS (
SELECT *
  FROM emp3
  WHERE max_emp_id = emp_id)
SELECT emp_id, ename, mod_date, emp_status
  FROM emp4
    EMP_ID ENAME MOD_DATE    EMP_STATUS
       103 MARY  22-JAN-2012 INACTIVE 
       102 john  21-JAN-2012 ACTIVE   
       106 JUHI  21-JAN-2012 ACTIVE   
       108 CHEN  22-JAN-2012 ACTIVE   
       110 james 22-JAN-2012 INACTIVE  5 rows selected.
Note: I manually re-ordered the result set so that it matches your expected results.
Edited by: user1983440 on Feb 21, 2013 10:55 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

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

  • SCCM CAS & Primary Site Server - Same SQL Database and Reporting Instance

    Hi Fellows,
    I need to know whether, for SCCM CAS, a dedicated/seperate SQL instance for SCCM CAS a mendatory requirement or recommendation?
    Or we can use the same SQL instance used by Primary Site Server?
    J.A

    There no technical reason not to have the CAS and Primary database in separate instances of the same remote SQL server. However if you are going to deploy a CAS that would suggest a very large number of clients and a very busy infrastructure. In that case
    I would RECOMMEND separate SQL servers.
    This is a good guide for SQL sizing (but it is only a guide)
    http://blog.coretech.dk/kea/system-center-2012-configuration-manager-sql-recommendations/
    Gerry Hampson | Blog:
    www.gerryhampsoncm.blogspot.ie | LinkedIn:
    Gerry Hampson | Twitter:
    @gerryhampson

  • Multiple cases based on Columns In SQL Query

    There is a SQL query given below, that query performs DateDIff operation by selecting max and min date according to
    TCard OR you can say id,
    here' the query
    SELECT
    --COUNT(DIFF)
    Count(DATEDIFF(D, MinDate, MaxDate)/30) AS DIFF
    FROM (
    SELECT
       MAX(TDate) AS MaxDate,
       MIN(TDate) AS MinDate
       FROM EDATA
       GROUP BY TCard
    )a
    Group by DATEDIFF(D, MinDate, MaxDate)/30
    Now i want to apply some kind of sorting in this query before performing DateDiff operation (sorting can be based on several parameters
    like age, name etc. but 1 at a time according to the cases) 
    Now I want to know How to apply cases over this query and where?

    You can apply sorting based on certain condition however you need to include those columns in your subquery. On custom sorting check out this article
    here:
    e.g.
    SELECT CountryName
    FROM   dbo.Country
    ORDER BY CASE WHEN
    CountryName = 'INDIA' THEN '1'
    WHEN CountryName = 'CHINA' THEN
    '2'
    ELSE CountryName END ASC
    If this post answers your query, please click "Mark As Answer" or "Vote as Helpful".

  • Is a Full Text Index search case sensitive or not in SQL Server 2012?

    I setup full text index on my contact table and am attempting to run a search on it using the following query:
    SELECT *
    FROM sysdba.Contact C
    WHERE CONTAINS(C.FirstName, 'Test')
    OR CONTAINS(C.LastName, 'Test')
    The problem is it's clearly running a case sensitive search. I did a quick search to find out how to change it to be case in-sensitive and found two pages (both for SQL Server 2012) with conflicting answers:
    1 - MSDN - "Query with Full-Text Search" - http://msdn.microsoft.com/en-us/library/ms142583(v=sql.110).aspx
    Case sensitivity
    Full-text search queries are case-insensitive. However, in Japanese, there are multiple phonetic orthographies in which the concept of orthographic normalization is akin to case insensitivity (for example, kana = insensitivity). This type of orthographic normalization
    is not supported.
    1 - TechNet - "Full-Text Search (SQL Server)" - http://technet.microsoft.com/en-us/library/ms142571(v=sql.110).aspx
    Full-text queries are
    not case-sensitive. For example, searching for "Aluminum" or "aluminum" returns the same results.
    Can someone please explain this? Is it possible to do it without it being case sensitive? If yes, how?
    (Sorry, I couldn't make those links b/c TechNet hasn't verified my account)
    Thank you for your time and help,
    Hanan

    Whats the collation setting for the columns? try using a case insensitive collation as below
    SELECT *
    FROM sysdba.Contact C
    WHERE CONTAINS(C.FirstName COLLATE SQL_Latin1_General_CP1_CI_AS, 'Test')
    OR CONTAINS(C.LastName COLLATE SQL_Latin1_General_CP1_CI_AS, 'Test')
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Problem in case of or condition in  where clause in case of leftouter joi.

    hi
    i am encountering a wierd problem.
    in a select query if i have a left outer join and a or condition in where clause the order of condition in or matters and if i use a to_char problem is solved.
    see query below
    select * from custsupp left outer join Salesperson s on custsupp.sales_rep = s.id ,state a where (CS_FLAG='C' or CS_flag ='B') and custsupp.state = a.id
    i have a single record in table custsupp with CS_FLAG ='B' the above does not return result. but if i move CS_FLAG='B' on left of or i.e
    select * from custsupp left outer join Salesperson s on custsupp.sales_rep = s.id ,state a where (CS_FLAG='B' or CS_flag ='C') and custsupp.state = a.id
    i get the rsult.
    also if i remove left outer join and keep order of condition as it is i get result i.e
    select * from custsupp ,state a where (CS_FLAG='C' or CS_flag ='B') and custsupp.state = a.id
    also if i add a to_char to co,umns CS_FLAG i get the result.
    select * from custsupp left outer join Salesperson s on custsupp.sales_rep = s.id ,state a where (to_char(CS_FLAG)='C' or to_char(CS_flag ='B')) and custsupp.state = a.id
    why it is so?
    CS_flag is of type nchar
    Shreyas
    Edited by: shreyasd on Jun 9, 2010 11:07 PM

    First if you don't want to take credit of the free sample then follow the below procedure:
    1. Do the GRN for all the three item and for the free item in the excise tab at the item level select the material as non cenvatable. Just remember to add base value of the item
    2.  If you want to capture the Part1 entry then just do the normal transaction and while posting the excise with J1IEX just remove the excise duties for the free item.
    3. For paying the vendor the excise amount, just do subsequent debit in the MIRO and in the details tab add in the unplanned delivery cost the amount that you want to pay for the excise duties
    Second case if you want to take credit of the duties:
    1. Do the Normal GRN process, add the base value and excise values for the free item.
    2. Post the Excise duites with J1iEX.
    3. The with the account entry you can settle the excise payment
    Hope this will help you
    Enjoyyyyyyyyyyy
    Akshit

  • APEX Interactive Report Compute Case with multiple conditions to highlight

    My ultimate is to highligt a row in an interactive report based on two conditions. I didn't see a way to use the highligt feature with two conditions. So I thought I would try to create a computation based on the two conditions. Then use that result for the highligting. Though I don't seem to be a be able to use multiple conditions in my computation Case statement. Is there a different syntax?
    Here is what I have:
    Case
      When  C = 'Open' and  I > 15 Then 'True'
      Else 'False'
    End The error I get is: Invalid computation expression. and
    Application Express 4.0.2.00.07
    Thanks!
    Edited by: cjmartin on Jan 10, 2012 10:57 AM

    I'm surprised no one responded to this. What I did to resolve this issue was create a nested case statement. I don't think this was a good solution, but I can't find anyone else giving input. I know I can create another computational column in the select statement for the report, but the 'Interactive Report' part is where this should be. I want my clients to calculate what they want. Kind of hard when you can not use an 'and' for a range criteria.

  • Count (case when) not working in sql

    Hi All,
    I am trying to find the count of members for a perticular date range, it seems not working correclty.
    Could any one help me out.
    here is the query...I am getting same output for all the cases..please help
    Select
    t
    .MemberNbr,t.patcom
    count(case
    when
    datediff(d,
    mbrs.DischargeDate,
    convert(datetime,convert(varchar(12),t.specificdateofservice),112))
    between
    -1
    and
    -365
    then t.MemberNbr
    else 0
    end)as
    edvisits365daysprior
    count(case
    when
    datediff(d,
    mbrs.DischargeDate,
    convert(datetime,convert(varchar(12),t.specificdateofservice),112))
    between 1
    and 3
    then t.MemberNbr
    else 0
    end)as
    edvisits3Days
    count(case
    when
    datediff(d,
    mbrs.DischargeDate,
    convert(datetime,convert(varchar(12),t.specificdateofservice),112))
    between 1
    and 30
    then t.MemberNbr
    else 0
    end)as
    edvisits30Days
    count(case
    when
    datediff(d,
    mbrs.DischargeDate,
    convert(datetime,convert(varchar(12),t.specificdateofservice),112))
    between 1
    and 60
    then t.MemberNbr
    else 0
    end)as
    edvisits60Days
    count(case
    when
    datediff(d,
    mbrs.DischargeDate,
    convert(datetime,convert(varchar(12),t.specificdateofservice),112))
    between 1
    and 90
    then t.MemberNbr
    else 0
    end)as
    edvisits90Days
    --,*--membernbr,specificdateofservice,count( membernbr)--, specificdateofservice)as visitcount--, patcom
    --Into #Tmp_PPCSEDCnt1
    From
    stg_tbl_InPatientPrepost Mbrs
    join
    #Tmp_MCCSEDVisits t
    on
    mbrs.MemberNbr=t.MemberNbr
    --where UPPER(t.MR_Line_Desc) in ('FOP EMERGENCY ROOM - HOSPITAL', 'FOP EMERGENCY ROOM Urgent Care',
    --'PROF ER VISITS AND OBSERVATION CARE')
    group
    by t.MemberNbr,t.patcom

    You may replace 0 as NULL and see how it works for you?
    eg:
    count(case when datediff(d, mbrs.DischargeDate,
    convert(datetime,convert(varchar(12),t.specificdateofservice),112)) 
    between -1 and -365 thent.MemberNbr else NULL end)as edvisits365daysprior

  • Update Statement(with Case) in PL/SQL Block

    Can we use Oracle case syntax (In a Update SQL)in a PL/SQL Block .
    UPDATE table_name a
    SET a.colum1 =
    case when a.col2 IN (SELECT col1
    FROM table_name1 b )
    then 'Y'
    else 'N'
    end
    It throws me an Error of code PLS-00103(This error message is from the parser. It found a token (language element) that is inappropriate in this context.)
    Is there any alternative...
    Thanx in Advance
    null

    Alas, PL/SQL has own SQL parser, and this parser dosn't know about CASE expressions (at least, it's true up to Oracle 8.1.7).
    Try to use DECODE instead, something like
    UPDATE table_name a
    SET a.colum1 =
    SELECT decode(count(*),0,'N','Y)
    FROM table_name1 b
    WHERE b.col1=a.colum1

  • Using Case when statement in catalog doesnt result in the correct sql

    I am running into an issue on my current project wherein, I am not able to see the correct formula in the physical query as I am seeing it in the logical query:
    Logical query:
    SET VARIABLE QUERY_SRC_CD='Report',SAW_SRC_PATH='/shared/Email/SFDC_InitRespTimel_Main';SELECT s_0, s_1, s_2, s_3, s_4, s_5 FROM (
    SELECT
    0 s_0,
    "CIN"."Calendar"."FIis Yr Nm" s_1,
    "CIN"."Calendar"."Fis Qtr Nm" s_2,
    "CIN"."SF Origin Dim"."Group" s_3,
    **CASE WHEN MIN("CIN"."SF_EailMsg_L"."Msg Dt") IS NOT NULL THEN SUM(TIMESTAMPDIFF(SQL_TSI_HOUR,MIN("SF_EailMsg_L"."Msg Dt"),"CIN"."SF_Case_L_Fact"."Created Dt"))/count("CIN"."SF_Case_L_Fact"."Case Number") END s_4,**
    **REPORT_AGGREGATE(CASE WHEN MIN("CIN"."SF_EailMsg_L"."Msg Dt") IS NOT NULL THEN SUM(TIMESTAMPDIFF(SQL_TSI_HOUR,MIN("SF_EailMsg_L"."Msg Dt"),"CIN"."SF_Case_L_Fact"."Created Dt"))/count("CIN"."SF_Case_L_Fact"."Case Number") END BY "CIN"."Calendar"."Fis Qtr Nm","CIN"."SF Origin Dim"."Group") s_5**
    FROM "CIN"
    WHERE
    (("Calendar"."FISCAL_YEAR_NAME" IN ('FY2011', 'FY2012', 'FY2013')) AND ("SF_EailMsg_L"."Status" = '3') AND ("Calendar"."FISCAL_QUARTER_NAME" <> 'Q1 FY2011'))
    ) djm ORDER BY 1, 2 ASC NULLS LAST, 3 ASC NULLS LAST, 4 ASC NULLS LAST
    Physical Query:
    select D1.c1 as c1,
    D1.c2 as c2,
    D1.c3 as c3,
    D1.c4 as c4
    from
    (select T13596.CRTDDT_DT as c1,
    T4813.FISCAL_YEAR_NAME as c2,
    T4813.FISCAL_QUARTER_NAME as c3,
    T13313.GRP as c4,
    ROW_NUMBER() OVER (PARTITION BY T4813.FISCAL_QUARTER_NAME, T13313.GRP, T13596.CRTDDT_DT ORDER BY T4813.FISCAL_QUARTER_NAME ASC, T13313.GRP ASC, T13596.CRTDDT_DT ASC) as c5
    from
    DW_SF_EMLMSSG_L T13275,
    SF_ORGN_L_DIM T13313,
    CIN_CALENDARS_DIM T4813,
    DW_SF_CS_L T13596 /* SF_CS_L_Fact */
    where ( T4813.CALENDAR_KEY = T13596.CRDT_KEY and T13275.PRNTID = T13596.ID and T13275.STTS = '3' and T13313.ORGN_KEY = T13596.ORGN_KEY and (T4813.FISCAL_YEAR_NAME in ('FY2011', 'FY2012', 'FY2013')) and T4813.FISCAL_QUARTER_NAME <> 'Q1 FY2011' )
    ) D1
    where ( D1.c5 = 1 )
    WITH
    SAWITH0 AS (select min(T13275.MSSGDT_DT) as c1,
    count(T13596.CSNMBR) as c2,
    T4813.FISCAL_YEAR_NAME as c5,
    T4813.FISCAL_QUARTER_NAME as c6,
    T13313.GRP as c7
    from
    DW_SF_EMLMSSG_L T13275,
    SF_ORGN_L_DIM T13313,
    CIN_CALENDARS_DIM T4813,
    DW_SF_CS_L T13596 /* SF_CS_L_Fact */
    where ( T4813.CALENDAR_KEY = T13596.CRDT_KEY and T13275.PRNTID = T13596.ID and T13275.STTS = '3' and T13313.ORGN_KEY = T13596.ORGN_KEY and (T4813.FISCAL_YEAR_NAME in ('FY2011', 'FY2012', 'FY2013')) and T4813.FISCAL_QUARTER_NAME <> 'Q1 FY2011' )
    group by T4813.FISCAL_QUARTER_NAME, T4813.FISCAL_YEAR_NAME, T13313.GRP)
    select D1.c1 as c1,
    D1.c2 as c2,
    D1.c3 as c3,
    D1.c4 as c4,
    D1.c5 as c5,
    D1.c6 as c6,
    D1.c7 as c7
    from
    (select D1.c1 as c1,
    D1.c2 as c2,
    min(D1.c1) over (partition by D1.c6, D1.c7) as c3,
    sum(D1.c2) over (partition by D1.c6, D1.c7) as c4,
    D1.c5 as c5,
    D1.c6 as c6,
    D1.c7 as c7,
    ROW_NUMBER() OVER (PARTITION BY D1.c6, D1.c7 ORDER BY D1.c6 ASC, D1.c7 ASC) as c8
    from
    SAWITH0 D1
    ) D1
    where ( D1.c8 = 1 )
    I want to know if you have seen this scenario earlier?
    Basically, the case statement in the logical sql is not getting executed correctly in the physical sql. Also,I see a SAWWITH0 in the query. Have you seen this before.
    If you have any inputs on how to fix this, please share.
    Thanks in advance.
    -Mayank Sharma

    Hello,
    This is the logical and physical query that I am getting now.
    My question is that, why am I not seeing the division operator (/) anywhere in the physical query. I am worried that the physical query is not being executed correctly.
    Please clarify:
    SET VARIABLE QUERY_SRC_CD='Report',SAW_DASHBOARD='/shared/Email/Email',SAW_DASHBOARD_PG='Initial Resp Time',SAW_SRC_PATH='/shared/Email/SFDC_InitRespTimel_Main';SELECT s_0, s_1, s_2, s_3, s_4, s_5 FROM (
    SELECT
    0 s_0,
    "CIN"."Calendar"."FIis Yr Nm" s_1,
    "CIN"."Calendar"."Fis Qtr Nm" s_2,
    "CIN"."SF Origin Dim"."Group" s_3,
    CASE WHEN MIN("CIN"."SF_EailMsg_L"."Msg Dt") IS NOT NULL THEN SUM(TIMESTAMPDIFF(SQL_TSI_HOUR,MIN("SF_EailMsg_L"."Msg Dt"),"CIN"."SF_Case_L_Fact"."Created Dt"))*1.0/count("CIN"."SF_Case_L_Fact"."Case Number")*1.0 END s_4,
    REPORT_AGGREGATE(CASE WHEN MIN("CIN"."SF_EailMsg_L"."Msg Dt") IS NOT NULL THEN SUM(TIMESTAMPDIFF(SQL_TSI_HOUR,MIN("SF_EailMsg_L"."Msg Dt"),"CIN"."SF_Case_L_Fact"."Created Dt"))*1.0/count("CIN"."SF_Case_L_Fact"."Case Number")*1.0 END BY "CIN"."Calendar"."Fis Qtr Nm","CIN"."SF Origin Dim"."Group") s_5
    FROM "CIN"
    WHERE
    (("Calendar"."FISCAL_YEAR_NAME" IN ('FY2011', 'FY2012', 'FY2013')) AND ("SF_EailMsg_L"."Status" = '3') AND ("Calendar"."FISCAL_QUARTER_NAME" <> 'Q1 FY2011'))
    ) djm ORDER BY 1, 2 ASC NULLS LAST, 3 ASC NULLS LAST, 4 ASC NULLS LAST
    [2012-10-25T22:20:58.000+00:00] [OracleBIServerComponent] [TRACE:2] [USER-23] [] [ecid: a5bccb33dce3bd12:-c49596b:13a898b42b5:-8000-0000000000007756] [tid: 601c] [requestid: 1d4c0001] [sessionid: 1d4c0000] [username: weblogic] -------------------- General Query Info: [[
    Repository: Star, Subject Area: CIN, Presentation: CIN
    [2012-10-25T22:20:58.000+00:00] [OracleBIServerComponent] [TRACE:2] [USER-18] [] [ecid: a5bccb33dce3bd12:-c49596b:13a898b42b5:-8000-0000000000007756] [tid: 601c] [requestid: 1d4c0001] [sessionid: 1d4c0000] [username: weblogic] -------------------- Sending query to database named CIN (id: <<177780>>), connection pool named CINADMIN: [[
    select D1.c1 as c1,
    D1.c2 as c2,
    D1.c3 as c3,
    D1.c4 as c4
    from
    (select T13596.CRTDDT_DT as c1,
    T4813.FISCAL_YEAR_NAME as c2,
    T4813.FISCAL_QUARTER_NAME as c3,
    T13313.GRP as c4,
    ROW_NUMBER() OVER (PARTITION BY T4813.FISCAL_QUARTER_NAME, T13313.GRP, T13596.CRTDDT_DT ORDER BY T4813.FISCAL_QUARTER_NAME ASC, T13313.GRP ASC, T13596.CRTDDT_DT ASC) as c5
    from
    DW_SF_EMLMSSG_L T13275,
    SF_ORGN_L_DIM T13313,
    CIN_CALENDARS_DIM T4813,
    DW_SF_CS_L T13596 /* SF_CS_L_Fact */
    where ( T4813.CALENDAR_KEY = T13596.CRDT_KEY and T13275.PRNTID = T13596.ID and T13275.STTS = '3' and T13313.ORGN_KEY = T13596.ORGN_KEY and (T4813.FISCAL_YEAR_NAME in ('FY2011', 'FY2012', 'FY2013')) and T4813.FISCAL_QUARTER_NAME <> 'Q1 FY2011' )
    ) D1
    where ( D1.c5 = 1 )
    [2012-10-25T22:20:58.000+00:00] [OracleBIServerComponent] [TRACE:2] [USER-18] [] [ecid: a5bccb33dce3bd12:-c49596b:13a898b42b5:-8000-0000000000007756] [tid: 601c] [requestid: 1d4c0001] [sessionid: 1d4c0000] [username: weblogic] -------------------- Sending query to database named CIN (id: <<178213>>), connection pool named CINADMIN: [[
    select D1.c1 as c1,
    D1.c2 as c2,
    D1.c3 as c3,
    D1.c4 as c4,
    D1.c5 as c5,
    D1.c6 as c6,
    D1.c7 as c7
    from
    (select D1.c1 as c1,
    D1.c2 as c2,
    min(D1.c1) over (partition by D1.c6, D1.c7) as c3,
    sum(D1.c2) over (partition by D1.c6, D1.c7) as c4,
    D1.c5 as c5,
    D1.c6 as c6,
    D1.c7 as c7,
    ROW_NUMBER() OVER (PARTITION BY D1.c6, D1.c7 ORDER BY D1.c6 ASC, D1.c7 ASC) as c8
    from
    (select min(T13275.MSSGDT_DT) as c1,
    count(T13596.CSNMBR) as c2,
    T4813.FISCAL_YEAR_NAME as c5,
    T4813.FISCAL_QUARTER_NAME as c6,
    T13313.GRP as c7
    from
    DW_SF_EMLMSSG_L T13275,
    SF_ORGN_L_DIM T13313,
    CIN_CALENDARS_DIM T4813,
    DW_SF_CS_L T13596 /* SF_CS_L_Fact */
    where ( T4813.CALENDAR_KEY = T13596.CRDT_KEY and T13275.PRNTID = T13596.ID and T13275.STTS = '3' and T13313.ORGN_KEY = T13596.ORGN_KEY and (T4813.FISCAL_YEAR_NAME in ('FY2011', 'FY2012', 'FY2013')) and T4813.FISCAL_QUARTER_NAME <> 'Q1 FY2011' )
    group by T4813.FISCAL_QUARTER_NAME, T4813.FISCAL_YEAR_NAME, T13313.GRP
    ) D1
    ) D1
    where ( D1.c8 = 1 )

  • Case Insensitive search and "IN" Clause - Open SQL

    Hi,
    I have some doubts regarding Open SQL:
    Is there any support for Case Insensitive Search in Open SQL, is it availabe by default?
    Is there any restriction on number of elements in "IN" Clause, in Open SQL, is there any default number?
    I have checked the [Open SQL Grammer|http://help.sap.com/saphelp_nwce711/helpdata/en/9b/f46cabaa874bc9a82234e8cf1d0696/frameset.htm] also, but nothing found there.
    Thanks,
    Piyush
    P.S I didn't find any other appropriate place to post this thread, let me know the correct categorization of Open SQL in case its wrong.

    Is there any support for Case Insensitive Search in Open SQL, is it availabe by default?
    When you are querying any strings, it is always case sensitive.
    Is there any restriction on number of elements in "IN" Clause, in Open SQL, is there any default number?
    I don't think there area any. IN opearator works like combined ORs and here you don't have any restrictions in fields number.
    Regards
    Marcin

  • Case insensitive search and "IN" Clause in Open SQL

    Hi,
    I have some doubts regarding Open SQL:
    - Is there any support for Case Insensitive Search in Open SQL, is it availabe by default?
    - Is there any restriction on number of elements in "IN" Clause, in Open SQL, is there any default number?
    I have checked the [Open SQL Grammer |http://help.sap.com/saphelp_nwce711/helpdata/en/9b/f46cabaa874bc9a82234e8cf1d0696/frameset.htm]also, but nothing found there.
    Thanks,
    Piyush
    P.S I didn't find any other appropriate place to post this thread, let me know the correct categorization of Open SQL in case its wrong.

    > I have some doubts regarding Open SQL:
    I believe that you've questions and not doubts...
    > - Is there any support for Case Insensitive Search in Open SQL, is it availabe by default?
    Nope, there is nothing like that. By default all supported database use a bytewise equal operator - case insensitivness needs to be programmed by hand.
    E.G. using UPPER(x)/LOWER(x) functions.
    Be aware that this disables the possibilities of index usage.
    > - Is there any restriction on number of elements in "IN" Clause, in Open SQL, is there any default number?
    Yes, there is a restriction and it differes between the different DBMS.
    Until recently you could have 2000 variables per statement with MaxDB.
    The current versions of DBSL and MaxDB Kernel now support up to 10000 variables per statement.
    Anyhow, in most cases, such a long in list can and should be avoided by using the FOR ALL ENTRIES construct. With this, the DBSL automatically splits the long IN list into smaller chunks and executes the statements several times.
    This is invisible to the ABAP report - it just gets the result set as usual.
    > P.S I didn't find any other appropriate place to post this thread, let me know the correct categorization of Open SQL in case its wrong.
    I guess in anyone of the DB forums is Ok.
    regards,
    Lars

  • Case sensitive within character literals in SQL Server and Oracle

    I am migrating SQL Server database to Oracle database by using Oracle Workbench.
    SQL Server is not case sensitive, but Oracle PL/SQL is case sensitive within character literals. for example, if sort the following string ('UN','Win', 'iS' ,'Ne','zS'), SQL Server will get ('iS', 'Ne','UN','Win','zS') order, but Oracle PL/SQL will return ('Ne','UN','Win','iS','zS') order.
    Anyone has idea how I can get same result as SQL Server without change PL/SQL code (I don't want to change "ORDER BY typename" to "ORDER BY UPPER(typename)" for every stored procedure).
    Thanks

    Jimmy,
    alter session set NLS_SORT=West_European;
    is the closest thing I know of, but UPPER() is the only sure way.
    West_European sort order is AaBbCc ... 0123456789
    usually sort order is 0123456789 ABC ... abc ...

  • SELECT CASE IN PL/SQL

    I NEED TO KNOW HOW TO RUN IN PL THE STATEMENT select case
    when ...
    thanks

    Hi
    SELECT with a CASE statement will not work in 8i when using
    static SQL. However if you are using dynamic SQL to execute it,
    then it will be fine. This is because the dynamic SQL statement
    is passed to the SQL engine for executing wheras static SQL is
    compiled by the PL/SQL compiler, which does not understand the
    complete SQL syntax.
    This will be fixed in 9i as well as PL/SQL in 9i also includes
    the CASE statement itself (outside of SQL).
    Guido

  • How to select a case sensitive value in SQL with C#

    Hello,
    I have an application that at the begining a user will login with a user name and password which is stored in the database. The SQL statement is as follows:
    "SELECT id_employee FROM employee WHERE employee_number='" + txtUserName.Text + "' AND passWord='" + txtPassword.Text + "'";
    For testing purposes I have set the password to the word test.   The problem is, if the user enters in TEST or TeSt or TESt  it will grant them access. How do I set it to force the correct case?
    I am using SQL 2005 for the database.
    Thanks!
    ~zero

    You can also set Collation while comparing strings:
    "SELECT id_employee FROM employee WHERE employee_number='" + txtUserName.Text + "' COLLATE Latin1_General_CS_AS AND passWord='" + txtPassword.Text + "'  COLLATE Latin1_General_CS_AS";
    All comments about not doing this type of quering using command string, instead of command with parameters, they are apsolutely right.
    Nevertheless i will have only username as a parameter in the command and password will be return value from procedure. I will check for equality of entered password and returned one from command in C# code, and C# is case sensitive. There is a good security model implemented for password in AdventureWorks sample database for SQL Server 2005, in table Person.Contact.
    That model use two fields for password, PasswordHash and PasswordSalt. PasswordSalt is randomly generated hash when password is modified and with that salt, password string is encrypted, which produce PasswordHash. So when you want to authenticate a user, execute a command that will return a row(PasswordHash and PasswordSalt) for entered username, and in application you will encrypt entered username with PasswordSalt. If generated string is equal with the one returned PasswordHash, then you have a valid login. If nothing is returned from command or they are not equal, you have invalid login.

Maybe you are looking for