Using CASE in a SQL predicate to return variable IN values ...

Environment:
Oracle EE 10.2.0.2 on AIX 5.3
I am trying to use a CASE statement in a SQL predicate to fill in the values needed in an 'IN' clause.
Here is my test case:
create table tt (model varchar2(10), brand varchar2(10));
insert into tt (model, brand) values ('modela','ajax');
insert into tt (model, brand) values ('modelb','ajax');
insert into tt (model, brand) values ('modelc','acme');
insert into tt (model, brand) values ('modeld','acme');
insert into tt (model, brand) values ('modele','acme');
insert into tt (model, brand) values ('modelf','zeus');
insert into tt (model, brand) values ('modelg','zeus');
insert into tt (model, brand) values ('modelh','mojo');
insert into tt (model, brand) values ('modeli','mojo');
insert into tt (model, brand) values ('modelj','mama');
Here is what I'm attempting to do. For a given starting letter for a brand I would like all the models printed out whose brand starts with the entered letter.
Here is what I started with:
select model, (case '&brandfirstletter'
when 'a' then '(''ajax'',''acme'')'
when 'z' then '(''zeus'')'
when 'm' then '(''mojo'')'
end) pred
from tt
where brand in
(case '&brandfirstletter'
when 'a' then '(''ajax'',''acme'')'
when 'z' then '(''zeus'')'
when 'm' then '(''mojo'')'
end);
When executed I get 'no rows selected'
I wanted to print out the results of my CASE statement just to be sure it was doing what I thought I wanted.
When I comment out the WHERE clause to see what the PRED values are I get:
gww@dwt1> /
Enter value for brandfirstletter: a
old 1: select model, (case '&brandfirstletter'
new 1: select model, (case 'a'
Enter value for brandfirstletter: a
old 8: -- (case '&brandfirstletter'
new 8: -- (case 'a'
MODEL PRED
modela ('ajax','acme')
modelb ('ajax','acme')
modelc ('ajax','acme')
modeld ('ajax','acme')
modele ('ajax','acme')
modelf ('ajax','acme')
modelg ('ajax','acme')
modelh ('ajax','acme')
modeli ('ajax','acme')
modelj ('ajax','acme')
I believe this is what I want the results of the CASE statement to look like when I select 'a' for the substitute variable but I don't get the output I would like from the table.
What am I missing?
Thanks very much!!
-gary

gwicke wrote:
select model, (case '&brandfirstletter'
when 'a' then '(''ajax'',''acme'')'
when 'z' then '(''zeus'')'
when 'm' then '(''mojo'')'
end) pred
from tt
where brand in
(case '&brandfirstletter'
when 'a' then '(''ajax'',''acme'')'
when 'z' then '(''zeus'')'
when 'm' then '(''mojo'')'
end);You can't do this.
ok, let's imagine you provide an 'a' as your substitution variable. What you get as a result is...
select model, (case 'a'
when 'a' then '(''ajax'',''acme'')'
when 'z' then '(''zeus'')'
when 'm' then '(''mojo'')'
end) pred
from tt
where brand in
(case 'a'
when 'a' then '(''ajax'',''acme'')'
when 'z' then '(''zeus'')'
when 'm' then '(''mojo'')'
end);
so if we logically remove the case statement as oracle would do when processing...
select model, ('(''ajax'',''acme'')') pred
from tt
where brand in ('(''ajax'',''acme'')');
Are you really going to have a brand that is stored as
(''ajax'',''acme'')as a single value?
You can't dynamically assign values to an IN list.

Similar Messages

  • Using case in prompt sql

    Hi,
    I'm trying to limit values for my dashboard prompt, but with condition.
    I have market channel as the first prompt, and customer as the second prompt. If market channel is, let's say, 'OEM', then I want to limit the second prompt only for specific customers (not all OEM). So as the other market channel, I want to pick only some customers for each of them. This is because the measure applied to only these specific customers.
    Thanks in advance.
    GT

    tHEHi,
    Thanku for reply.
    I used the same approach what did u reply. But still i am facing the similar issue once i say ok to the query.
    It is showing the following error:-
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 27002] Near <,>: Syntax error [nQSError: 26012] . (HY000)
    SQL Issued: {call NQSGetQueryColumnInfo('SELECT CASE WHEN ''MGMT $''=''MGMT $'' THEN SR_QUOTA_ACHIV_AGGR.MGMT_DOLLARS_MTD_AMT ELSE SR_QUOTA_ACHIV_AGGR.LGL_DOLLARS_MTD_AMT, GEO_DIM.AREA, GEO_DIM.AREA_DESC, ORDER_SPLIT.BOOKED_DT, ORDER_SPLIT.ORD_SHIP_TO_SITE_CITY, ORDER_SPLIT.ORD_SHIP_TO_SITE_NBR, ORDER_SPLIT.ORD_SOLD_TO_SITE_CITY, ORDER_SPLIT.ORD_SOLD_TO_SITE_NBR, SR_QUOTA_ACHIV_AGGR.PROD_LINE_CD, SR_QUOTA_ACHIV_AGGR.QUOTA_CREDIT_COUNTRY_KEY, SR_QUOTA_ACHIV_AGGR.SALES_ORG_ID FROM ROAD_RUNNER')}
    SQL Issued: SELECT CASE WHEN 'MGMT $'='MGMT $' THEN SR_QUOTA_ACHIV_AGGR.MGMT_DOLLARS_MTD_AMT ELSE SR_QUOTA_ACHIV_AGGR.LGL_DOLLARS_MTD_AMT, GEO_DIM.AREA, GEO_DIM.AREA_DESC, ORDER_SPLIT.BOOKED_DT, ORDER_SPLIT.ORD_SHIP_TO_SITE_CITY, ORDER_SPLIT.ORD_SHIP_TO_SITE_NBR, ORDER_SPLIT.ORD_SOLD_TO_SITE_CITY, ORDER_SPLIT.ORD_SOLD_TO_SITE_NBR, SR_QUOTA_ACHIV_AGGR.PROD_LINE_CD, SR_QUOTA_ACHIV_AGGR.QUOTA_CREDIT_COUNTRY_KEY, SR_QUOTA_ACHIV_AGGR.SALES_ORG_ID FROM ROAD_RUNNER
    Thanks

  • How to extract a tags content using DOMParser in PL/SQL

    The structure of my xml-document is as below:
    <Reply>
    <Errors>
    <Error Number="0">No Error Occured</Error>
    </Errors>
    </Reply>
    Using DOMParser in PL/SQL iam able to extract the value associated with the 'Number' attribute in the <Error> tag, but i am unable to extract the text (error message => "No Error Occured") embedded in the <Error> tag.
    How should i go about? Provide any hints, if possible sample code.
    Thanks in Advance.
    RamPrasad.

    In order to get the text, you need to check the child node, as the text really lives by itself.
    For example I modified the DOMSAMPLE to dislay the text not just the attributes. I have included the code below.
    I hope that this helps you.
    for i in 0..len-1 loop
    n := xmldom.item(nl, i);
    dbms_output.put(xmldom.getNodeName(n) || ' ');
    n := xmldom.getfirstchild(n);
    IF xmldom.getnodetype(n) = xmldom.Text_Node THEN
    v_val := xmldom.getnodevalue(n);
    dbms_output.put_line(v_val);
    END IF;
    end loop;
    I really think that the XML tools in Oracle would be much more useful, is they were accompanied by complete documentation.
    The structure of my xml-document is as below:
    <Reply>
    <Errors>
    <Error Number="0">No Error Occured</Error>
    </Errors>
    </Reply>
    Using DOMParser in PL/SQL iam able to extract the value associated with the 'Number' attribute in the <Error> tag, but i am unable to extract the text (error message => "No Error Occured") embedded in the <Error> tag.
    How should i go about? Provide any hints, if possible sample code.
    Thanks in Advance.
    RamPrasad.

  • Display returns latest data value rather than maximum data value.

    I have requested the Maximum value using the Statistics VI.  The display returns the latest value rather than the maximum.  I think it may have to do with specifying the sample size or data packet size but I don't know how to do that.

    You probably are only taking a single reading with the DAQ Assistant and the Statistics function expects an array to determine the max value in that array. There are a couple ways to do what you want. One way is to use the Array Min & Max Single Point function (Signal Processing>Point by Point>Other Functions). This has a sample length input and a reset input. Another way is to create an array with a shift register and use the Statistics function or just the Array Min & Max function. You could limit the size of the array with Array Subset for example.
    To attach a file to your post, look below the message body. There is a Attachment field with a browse button.
    Message Edited by Dennis Knutson on 06-29-2007 09:41 AM
    Attachments:
    Max value.PNG ‏7 KB

  • How to use a select list value in a PL/SQL function body returning SQLquery

    Hi Friends,
    I have a select list P6_TEST with values 'nav' anf 'jyo'. I am trying to create a report using "SQL Query (PL/SQL
    function body returning SQL query)". In my report query can i check if P6_TEST='nav' and do something like the
    code shown below.How can i do that.
    DECLARE
    v_sql VARCHAR2(3000);
    BEGIN
    IF :P6_TEST = 'nav' THEN
    v_sql :=
    'SELECT
    * from department';
    ........................Thanks,
    Nav

    Nav:
    What you have should work. Give it a go. Post back if you run into issues.
    Varad

  • Help needed in SQL performance - Using CASE in SQL statement versus 2 query

    Hi,
    I have a requirement to find count from a bunch of tables.
    The SQL I have gives the count of all members.
    I have created 2 queries to find count of active and inactive members.
    The key difference is only the active dates.
    Each query takes 20 seconds to execute.
    I modified the SQL to use CASE statement in the SELECT.
    So after the data is fetched the CASE statement will evaluate the active date and gives 2 counts (active and inactive)
    Is it advisable to use this approach. Will CASE improve SQL performance ? I have to justify this.
    Please let me know your thoughts.
    Thanks,
    J

    Hi,
    If it can be done in single SQL do it in single SQL.
    You said:
    Will CASE improve SQL performance There can be both cases to prove if the performance is better or worse.
    In your case you should tell us how it is.
    Regards,
    Bhushan

  • SQL Query (PL/SQL function body returning SQL query) when using to_char

    we are trying to build a report page of Type SQL Query (PL/SQL function body returning SQL query).
    our query is so simple, we need to extract the month from the recording_date column.
    declare
    l_query varchar2(1000);
    begin
    l_query:='select to_char(recording_date,'MM')from re_productive';
    return l_query;
    end;
    but we are having the following problem for this query
    Function returning SQL query: Query cannot be parsed within the Builder. If you believe your query is syntactically correct, check the generic columns checkbox below the region source to proceed without parsing.
    (ORA-06550: line 4, column 42: PLS-00103: Encountered the symbol "MON" when expecting one of the following: . ( * @ % & = - + ; < / > at in is mod remainder not rem <> or != or ~= >= <= <> and or like between || multiset member SUBMULTISET_ The symbol ". was inserted before "MON" to continue.)
    Notes:
    1-the query is correct and it was tested under Toad and SQL Plus.
    2- we tried Use Generic Column Names (parse query at runtime only) option but we get the same problem.
    any quick help please.

    Hi
    You haven't escaped your quotes in the string. Try this...
    DECLARE
    l_query VARCHAR2(32767);
    BEGIN
    l_query:= 'select to_char(recording_date,''MM'') from re_productive';
    RETURN l_query;
    END;Cheers
    Ben

  • Pure SQL and Border Use Cases?

    Hi Gurus
    I was developing a DB Adapter to select data from Shipping tables. I did it by polling as well as with Custom SQL. While using the custom SQL I got the following error in my domain.log
    (my query that I wrote) failes, Caused by java.sql.SQLException: Invalid column index.
    The Pure SQL option is for border use cases only and provides simple yet minimal functionality. Possibly try the "Perform an operation on a table" option instead.
    What is a border use case, how do I decide that. So BPEL support the custom sql option very loosely?
    Thx

    The thing is that XSLT often doesn't deliver the functionality required when it comes to times.
    You suggest appening "Z" to the time but this means that the time is now in UTC time. What if the system from where the date is being converted is running in NZ using local time? Other systems that recieve the date (and correctly handle the time zone) will now have a time that is out by a number of hours.
    You often can't ignore the time zone (drop the 'Z') as if you send the time to a system it has to either assume the time is local to it (which may not be the case... the other system coudl be in a different time zone) or assume the time is UTC (I think crossfire does this by default).
    Typically can't just append a time zone (e.g. +11:00) either as many places have daylight savings so the value to appended is variable (you then need some way of determining what the value is... either Java Embedding or a Service).
    As you mention it does depend on the use case but in many circumstances using Jaba Embedding, not as suggested above but with the appropriate Java.util.Calendar classes, is the best way to handle date and time in BPEL. Even still you need to ascertain the format of times external to the system and ensure you parse them correctly.
    ANd even if you do all this you can still run into problems. I've seen a real world example where two systems which both handled time zones correctly and had previously been working together for quite a while, satrted reporting different times. It turns out that only one of them had had the most recent Java Time Zone patches applied and there had been a change in the dates for daylight savings here (Australia). Be warned!

  • Using Package to produce pl/sql function body returning sql query Report

    I have existing code that we want to use in building reports in APEX. We are needing to modify it slightly to handle some new requirements, but would like to use them in reports based upon SQL query (pl/sql function body returning sql query) functionality.
    Any suggestions as how to call these in an APEX report region?
    Thank you,
    Tony Miller
    UTMB/EHN

    Hi Tony-
    I am also v new to Apex and you may have answered a question I was in search of. I, however, now have a couple more. First a bit of background-- Like in your situation, my college has a lot of existing code (400 +) that we need to get into Apex. The majority of this canned code contains one/both: 1) many lines, sometimes containing multiple select statements 2) imbedded create table & view statements (temp user owned). Up until reading your post, I was unable to figure out an easy way of getting this existing code into the product. Thanks. Now the questions, do you know how I would go about dealing with the create tables/views. I've read some posts on this forum which suggest temporary tables being unstable in this environment. Also, do you know if there's a size limitation when passing sql code via a function?
    As you may/may not be able to tell, I'm a bit lost right now... so any info you can provide would be appreciated. Thanks.
    Don

  • Getting PL/SQL:ORA-00933 when using CASE logic as a control structure

    Hello Everybody,I have created a PL/SQL block(Control Structure) to calculate bonus of employees based on salary of the employee,but I get errors like ORA-00933 and ORA-06550.Given below is the PL/SQL block which I tried to implement
    SQL> DECLARE
    2
    3 v_EMPNO NUMBER(7,2):= &p_EMPNO;
    4 v_SAL EMP.SAL%TYPE;
    5 v_BONUS NUMBER;
    6
    7 BEGIN
    8 SELECT SAL
    9 FROM EMP
    10 INTO v_SAL
    11 WHERE EMPNO = v_EMPNO;
    12
    13 v_BONUS :=
    14 CASE v_SAL
    15 WHEN v_SAL = 0 THEN 0
    16 WHEN v_SAL < 1500 THEN (0.1*v_SAL)
    17 WHEN v_SAL BETWEEN 1500 AND 3000 THEN (0.15*v_SAL)
    18 WHEN v_SAL > 3000 THEN (0.20*v_SAL)
    19 END;
    20
    21 DBMS_OUTPUT.PUT_LINE(' EMPNO '||v_EMPNO||' SALARY '||v_SAL||' BONUS '||V_BONUS);
    22
    23 END;
    24 /
    Enter value for p_empno: 7100
    old 3: v_EMPNO NUMBER(7,2):= &p_EMPNO;
    new 3: v_EMPNO NUMBER(7,2):= 7100;
    INTO v_SAL
    ERROR at line 10:
    ORA-06550: line 10, column 7:
    PL/SQL: ORA-00933: SQL command not properly ended
    ORA-06550: line 8, column 7:
    PL/SQL: SQL Statement ignored
    Is it that I can not use "CASE" as a control structure in the above block , when I code
    "SELECT SAL
    FROM EMP
    INTO v_SAL
    WHERE EMPNO = v_EMPNO;" to get v_SAL and then use it in CASE exp to calculate a value for v_Bonus.
    Kindly let me know.

    Hi,
    The CASE Expression is also available in PL/SQL.
    Try this code:
    DECLARE
       V_EMPNO   NUMBER (7, 2)  := 7788;
       V_SAL     EMP.SAL%TYPE;
       V_BONUS   NUMBER;
    BEGIN
       SELECT SAL
         INTO V_SAL
         FROM EMP
        WHERE EMPNO = V_EMPNO;
       V_BONUS :=
          CASE
             WHEN V_SAL = 0
                THEN 0
             WHEN V_SAL < 1500
                THEN (0.1 * V_SAL)
             WHEN V_SAL BETWEEN 1500 AND 3000
                THEN (0.15 * V_SAL)
             WHEN V_SAL > 3000
                THEN (0.20 * V_SAL)
          END;
       DBMS_OUTPUT.PUT_LINE (   ' EMPNO '
                             || V_EMPNO
                             || ' SALARY '
                             || V_SAL
                             || ' BONUS '
                             || V_BONUS
    END;As you are Using,Comparison Expression to find a match, Your Searched CASE Expression should be something like this.
    DECLARE
      sal       NUMBER := 2000;
      sal_desc  VARCHAR2(20);
    BEGIN
      sal_desc := CASE
                     WHEN sal < 1000 THEN 'Low'
                     WHEN sal BETWEEN 1000 AND 3000 THEN 'Medium'
                     WHEN sal > 3000 THEN 'High'
                     ELSE 'N/A'
                  END;
      DBMS_OUTPUT.PUT_LINE(sal_desc);
    END;If you are Using CASE as a Value matching then your piece of code should be like this..
    DECLARE
      deptno     NUMBER := 20;
      dept_desc  VARCHAR2(20);
    BEGIN
      dept_desc := CASE deptno
                     WHEN 10 THEN 'Accounting'
                     WHEN 20 THEN 'Research'
                     WHEN 30 THEN 'Sales'
                     WHEN 40 THEN 'Operations'
                     ELSE 'Unknown'
                   END;
      DBMS_OUTPUT.PUT_LINE(dept_desc);
    END;Thanks,
    Shankar

  • Retrieving PL/SQL Table Type returned by stored procedure using Java.

    Hi All,
    I am facing an issue in a Stored Procedure (SP) which returns Table Type, the PL/SQL complex type.
    Below mentioned is how my stored procedure looks like.
    CREATE OR REPLACE package sp_test_pkg as
    TYPE v_value_table_type is table of SW_VALID_CODE.swValue%Type
    index by binary_integer;
    v_swRMAStatus v_value_table_type;
    procedure sp_test
    (locale      in int,
              name      in SW_CODE.swName%Type,
              v_value_table out v_value_table_type,
    batch_size in int,
    out_batch_size in out int,
    status out int);
    end sp_test_lcode_code_pkg;
    My java program to access this stored procedure is as given below:
    import java.sql.*;
    import oracle.jdbc.driver.*;
    public class OracleTest {       
         public static void main(String args[]) {
         Connection con = null;
    OracleCallableStatement cstmt = null;
    String url = "url";
         String userName = "username";     
         String password = "password";
    try
              DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());     
              con = DriverManager.getConnection(url, userName, password);
         cstmt = (OracleCallableStatement)con.prepareCall("begin " +
              "sp_test_pkg.sp_test_pkg(?,?,?,?,?,?); end;");
              cstmt.setInt(1, 1);
         cstmt.setString(2, "Test");
              cstmt.registerOutParameter(3, OracleTypes.ARRAY);
              cstmt.setInt(4, 10);
              cstmt.setInt(5, 1);
              cstmt.registerOutParameter(5, Types.INTEGER);
              cstmt.registerOutParameter(6, Types.INTEGER);
              cstmt.execute();
    } catch(Exception ex) {
    ex.printStackTrace(System.err);
    } finally {
    if(cstmt != null) try{cstmt.close();}catch(Exception _ex){}
    if(con != null) try{con.close();}catch(Exception _ex){}
    When i execute this java program, i get the following error:
    java.sql.SQLException: Parameter Type Conflict: sqlType=2003
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:187)
         at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:229)
         at oracle.jdbc.driver.OracleCallableStatement.registerOutParameterBytes(OracleCallableStatement.java:245)
         at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:389)
         at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(OracleCallableStatement.java:452)
         at OracleTest.main(OracleTest.java:49)
    I am not sure where i am going wrong. I have never worked on such complex types before. I want to retrieve the complex table type returned by the stored procedure using my java source code.
    Can anyone please help me out in resolving this issue?. This is very urgent.

    JDBC does not recognise types declared in PL/SQL. This is documented in the Dev Guide. [Find out more|http://download-west.oracle.com/docs/cd/B10501_01/java.920/a96654/oraarr.htm#1057625].
    The only work around would be to build a wrapper which calls your existing PL/SQL procedures and returns a SQL type instead. Obviously not knowing your precise scenario I have no idea how much work this entails for you. It may be worth building a code generator.
    Cheers, APC
    blog: http://radiofreetooting.blogspot.com

  • Using CASE WHEN in PL/SQL package

    I am trying to convert the values in a selected column into 1 and 0 so that I can display all 1s in one column, all 0s in another. I am doing this in a PL/SQL package. However ORACLE compiler does not like the CASE construct.
    Does anyone know how to group values in a column into several new columns. If CASE WHEN construct is not doable in PL/SQL, what alternatives are there? Thanks.
    /******* My package starts here *******/
    CREATE OR REPLACE PACKAGE TEST_NEED AS
    PROCEDURE procTEST_NEED(STARTING_DATE IN VARCHAR2);
    END CVRR_MON_NEED;
    CREATE OR REPLACE PACKAGE BODY TEST_NEED
    AS
    PROCEDURE procTEST_NEED(STARTING_DATE IN VARCHAR2)
    IS
    TEST_START DATE := TO_DATE(STARTING_DATE,'MM/DD/YYYY');
    CURSOR v_Cursor IS
    SELECT A.D_CODE, A.M_CODE, TEST_START , C.C_NAME,C.P_ID,
    SUM(CASE WHEN MONTHS_BETWEEN(SYSDATE, D.P_DOB)/12 > 40 AND MONTHS_BETWEEN(SYSDATE, D.P_DOB)/12 <85 AND B.B_CODE IN '11.1','222.2','272.4') THEN 1 ELSE 0 END) QUALIFIED
    FROM A, B, C, D
    WHERE A.ID = B.B_ID
    AND RTRIM(A.P_CODE) = C.P_CODE
    AND A.P_ID = D.P_ID
    AND A.P_ID < 99999999999999999999
    AND A.E_DATETIME < SYSDATE
    GROUP BY A.D_CODE, A.M_CODE, TEST_START , C.C_NAME,C.P_ID;
    v_RecordHolder v_Cursor%ROWTYPE;
    BEGIN
    OPEN v_Cursor;
    FETCH v_CursorINTO v_RecordHolder ;
    WHILE v_Cursor%FOUND LOOP
    look for records in another table with matching keys of the cursor
    if found then update by incrementing the existing values in the matching records with values of the current currsor row
    else insert the current cursor row
    FETCH v_Cursor INTO v_RecordHolder ;
    END LOOP;
    END procTEST_NEED;
    END TEST_NEED;

    I am trying to convert the values in a selected
    column into 1 and 0 so that I can display all 1s in
    one column, all 0s in another. I am doing this in a
    PL/SQL package. However ORACLE compiler does not
    like the CASE construct.
    Does anyone know how to group values in a column into
    several new columns. If CASE WHEN construct is not
    doable in PL/SQL, what alternatives are there?
    Thanks.
    CURSOR v_Cursor IS
    SELECT A.D_CODE, A.M_CODE, TEST_START ,
    , C.C_NAME,C.P_ID,
    SUM(CASE WHEN MONTHS_BETWEEN(SYSDATE, D.P_DOB)/12 >
    40 AND MONTHS_BETWEEN(SYSDATE, D.P_DOB)/12 <85 ANDB.B_CODE IN '11.1','222.2','272.4') THEN 1 ELSE 0
    END) QUALIFIEDUse the Decode function. This has been around in oracle SQL for ages and works like a case construct.
    You would do something like
    select ...
    sum( decode (MONTHS_BETWEEN(SYSDATE, D.P_DOB)/12 >
    40 AND MONTHS_BETWEEN(SYSDATE, D.P_DOB)/12 <85 AND
    B.B_CODE IN ('11.1','222.2','272.4') 1,0 )

  • Need help in this sql query to use Case Statement

    hi All,
    I have the below query -
    SELECT DISTINCT OFFC.PROV_ID
    ,OFFC.WK_DAY
    ,CASE
    WHEN OFFC.WK_DAY ='MONDAY' THEN 1
    WHEN OFFC.WK_DAY ='TUESDAY' THEN 2
    WHEN OFFC.WK_DAY ='WEDNESDAY' THEN 3
    WHEN OFFC.WK_DAY ='THURSDAY' THEN 4
    WHEN OFFC.WK_DAY ='FRIDAY' THEN 5
    WHEN OFFC.WK_DAY ='SATURDAY' THEN 6
    WHEN OFFC.WK_DAY ='SUNDAY' THEN 7
    END AS DOW
    ,OFFC.OFFC_OPENG_TIME
    ,OFFC.OFFC_CLSNG_TIME
    FROM GGDD.PROV_OFFC_HR OFFC
    WHERE OFFC.PROV_ID='0000600'
    WITH UR;
    this query is bringing results in 6 differnt rows with opening and closing time for each day separately. I want to generate the data in one row with each day having opening and closing time, so for 7 days, total 14 columns with opening and closing time. But i am not able to do that using case statement.
    can somebody help me in achieving that.
    thanks,
    iamhere

    Hi,
    Welcome to the forum!
    That's called a Pivot .
    Instead of having 1CASE expression, have 14, one for the opening and one for the closing time each day, and do GROUP BY to combine them onto one row.
    SELECT       OFFC.PROV_ID
    ,       MIN (CASE WHEN OFFC.WK_DAY ='MONDAY'    THEN OFFC.OFFC_OPENG_TIME END)     AS mon_opn
    ,       MIN (CASE WHEN OFFC.WK_DAY ='MONDAY'    THEN OFFC.OFFC_CLSNG_TIME END)     AS mon_cls
    ,       MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY'   THEN OFFC.OFFC_OPENG_TIME END)     AS tue_opn
    ,       MIN (CASE WHEN OFFC.WK_DAY ='TUESDAY'   THEN OFFC.OFFC_CLSNG_TIME END)     AS tue_cls
    FROM        GGDD.PROV_OFFC_HR OFFC
    WHERE       OFFC.PROV_ID     = '0000600'
    GROUP BY  offc.prov_id
    ;This assumes there is (at most) only one row in the table for each distinct prov_id and weekday. If not, what do you want to do? Post a little sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
    The staement above works in Oracle 8.1 and up, but there's a better way (SELECT ... PIVOT) available in Oracle 11. What version are you using? (It's always a good idea to include this when you post a question.)
    Edited by: Frank Kulash on Jan 6, 2011 8:22 PM

  • Sql proposed to use case statement

    Hi All
    Can anyone help me here
    This code works fine,here inthe inner sub queries(b,c,d,e,f),i am getting the weekly counts of usage data from the table mf_wer_OBI_USAGE_reqq.
    As this is hitting same table with the similar set of queries so i was adviced to use case statement by taking the wk_1...5 in variable and making the query better
    I am unable to figure out how to proceed.
    Appreciate your help here.
    Thanks
    create table mf_wer_OBI_USAGE_reqq_WK
    as select x.user_name id,x.mon MONTH_COUNT,x.wk_1 WEEK1_COUNT,x.wk_2 WEEK2_COUNT,x.wk_3 WEEK3_COUNT,x.wk_4 WEEK4_COUNT,x.wk_5 WEEK5_COUNT,x.subject_area_name,
    y.EMP_FIRST_NAME FIRSTNAME,y.EMP_LAST_NAME SURNAME,y.E_MAIL_ADDRESS USER_MAILID,y.ouc OUC
    from (select a.user_name,a.mon,a.subject_area_name,b.wk_1,c.wk_2,d.wk_3,e.wk_4,f.wk_5
    from (select user_name,sum(count_us_st) mon,subject_area_name from mf_wer_OBI_USAGE_reqq group by user_name,subject_area_name) a,
    (select user_name,sum(count_us_st) wk_1,subject_area_name from mf_wer_OBI_USAGE_reqq where extract(day from start_dt) between 1 and 7
    group by user_name,subject_area_name) b,
    (select user_name,sum(count_us_st) wk_2,subject_area_name from mf_wer_OBI_USAGE_reqq where extract(day from start_dt) between 8 and 14
    group by user_name,subject_area_name) c,
    (select user_name,sum(count_us_st) wk_3,subject_area_name from mf_wer_OBI_USAGE_reqq where extract(day from start_dt) between 15 and 21
    group by user_name,subject_area_name) d,
    (select user_name,sum(count_us_st) wk_4,subject_area_name from mf_wer_OBI_USAGE_reqq where extract(day from start_dt) between 22 and 28
    group by user_name,subject_area_name) e,
    (select user_name,sum(count_us_st) wk_5,subject_area_name from mf_wer_OBI_USAGE_reqq where extract(day from start_dt) between 29 and 31
    group by user_name,subject_area_name) f
    where a.user_name=b.user_name(+)
    and a.subject_area_name=b.subject_area_name(+)
    and a.user_name=c.user_name(+)
    and a.subject_area_name=c.subject_area_name(+)
    and a.user_name=d.user_name(+)
    and a.subject_area_name=d.subject_area_name(+)
    and a.user_name=e.user_name(+)
    and a.subject_area_name=e.subject_area_name(+)
    and a.user_name=f.user_name(+)
    and a.subject_area_name=f.subject_area_name(+)) x,
    dm_employee y
    where x.user_name=y.id and
    y.active_flg='Y';

    Swas_fly wrote:
    This code works fineIf it's fine, why try to fix it?
    Post your table (only the relevant columns as a CREATE TABLE statement) and some sample data (INSERT into) and your required output.
    Post your code between these tags:                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                

  • Conditional display using Pl/SQL function body returning a boolean

    I am having issues with conditional display of a report.
    I have to select lists: p50_facility and p50_supervisor.
    I have entered the below pl/sql function body returning a boolean
    Begin
    if (:p50_facility is null or
    :p50_supervisor is null) THEN
    Return False;
    Else
    Return True;
    End if;
    End;
    No matter what values my items are set to (null, not null), the report shows.
    What am I doing wrong?

    Hi,
    The values for the lists will be null only until the first time the page is submitted. Thereafter, the value is likely to be '%null%'
    You will need to do something like:
    BEGIN
    IF (:P50_FACILITY IS NULL OR :P50_FACILITY = '%' || 'null%' OR :P50_SUPERVISOR IS NULL OR :P50_SUPERVISOR = '%' || 'null%') THEN
      RETURN FALSE;
    ELSE
      RETURN TRUE;
    END IF;
    END;Andy

Maybe you are looking for

  • How can I block spam e-mail when the "from address" keeps changing?

    How can I block a spam mail sender when that spamer uses a different e-mail address everytime!  I have set up a rule with the spamers name (which does not change) and setting the rule to "is equal to" but it is not working. 

  • I have lost most of my purchased music!! HELP!

    I open up my iTunes on my laptop (windows 7), then plug in my iPod. (My iPod is only 2nd generation, I need to get a new one!! : P) It starts to sync automatically. I think - 'ok dont worry, just carry on!' When it has finished syncing/charging, i go

  • Problems importing new values into existing hierarchy

    I have a hierarchy setup with name and code fields. I have already imported the majority of the records and manually setup the hierarchy in Data Manager (as we never had hierarchy setup in the past). I now have 100 or so new entries to add to this ta

  • Paypal - break line in 2 on checkout page?

    In paypal does anyone know if its possible to break  the information on the checkout screen into to 2 or more lines? <input type="hidden" name="item_name" value="<?php echo $breakTitle; ?><br/><?php echo $breakDate; ?>"> paypal doesn't seem to make m

  • HT5557 iBook Author does not open file

    A client submit by email a file with extension *.book. I know is an iBook Author file but I don't understand why I cannot open it. Any help will be appreciate it. Best regards,