How to use multiple search conditions in the where clause

Hi,
Below is my query
/****** Script for SelectTopNRows command from SSMS  ******/
SELECT distinct 
ctacct,sum(GLMN02)
  FROM [ODS].[Staging].[tODS_INF_GLPCT]
  inner join 
  [ODS].[Staging].[tODS_INF_GLPGL] ON tODS_INF_GLPCT.CTPAGE = tODS_INF_GLPGL.GLPAGE
  where 
  CTACCT like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-63020-4110%'
This one gives me the exact result i want, now if i add one more to my where clause like this
/****** Script for SelectTopNRows command from SSMS  ******/
SELECT distinct 
ctacct,sum(GLMN02)
--,ctdesc,CTPAGE
--SUM(GLMN02)
  FROM [ODS].[Staging].[tODS_INF_GLPCT]
  inner join 
  [ODS].[Staging].[tODS_INF_GLPGL] ON tODS_INF_GLPCT.CTPAGE = tODS_INF_GLPGL.GLPAGE
  where 
  CTACCT like'[0-9][0-9][0-9]-[0-9][0-9][0-9]-63020-4110%' or
  CTACCT like '[0-9][0-9][0-9]-[0-9][0-9][0-9]-63020-4115%'
This query doesnt give me the exact values instead it gives me all the weird values.Can someone please help me with how to work on this where clause?
Thanks

Hi Patrick,
This is what i ve tried earlier and it isnt working .If i use the first query
/****** Script for SelectTopNRows command from SSMS  ******/
SELECT distinct 
ctdesc,SUM(GLMN02)
--,ctdesc,CTPAGE
--SUM(GLMN02)
  FROM [ODS].[Staging].[tODS_INF_GLPCT]
  inner join 
  [ODS].[Staging].[tODS_INF_GLPGL] ON tODS_INF_GLPCT.CTPAGE = tODS_INF_GLPGL.GLPAGE
  where 
 CTAcct LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9]-63020-4110%'
   --OR
   --CTAcct LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9]-63020-4115%'
  and GLYEAR = 2014
  and CTDESC = 'Sales'
  group by ctdesc
The result set is 
Sales                        
-182273.96
And if i use the second query
SELECT distinct 
ctdesc,SUM(GLMN02)
--,ctdesc,CTPAGE
--SUM(GLMN02)
  FROM [ODS].[Staging].[tODS_INF_GLPCT]
  inner join 
  [ODS].[Staging].[tODS_INF_GLPGL] ON tODS_INF_GLPCT.CTPAGE = tODS_INF_GLPGL.GLPAGE
  where 
 CTAcct LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9]-63020-4110%'
 OR
   CTAcct LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9]-63020-4115%'
  and GLYEAR = 2014
  and CTDESC = 'Sales'
  group by ctdesc
The result set i get is 
Sales                        
-1455441.08
And i verified that  CTAcct LIKE '[0-9][0-9][0-9]-[0-9][0-9][0-9]-63020-4115%'
this second line of where clause has not desc as Sales.
I am not sure whats causing the difference in the values.
Can you please help me with this?
Thanks

Similar Messages

  • Like condition in the where clause.

    Dear All,
    I have created a new form using a datablock wizard with one table.
    Now i placed a text box and a button in the same form. I will be entering the value in the text box and based up the condition in the where clause of the datablock property i am restricting the values where the column name is thetext box value.
    Now my problem is i need to give a string value in the text box and the datablokc has to populate based up the like condtion. I dont know the syntax how to give like condition in the where clause of the property pallet.
    Please help me in this.
    Thanks in advance.
    Cheers,
    Raju

    Maybe try this ...
    Create a button to query the block :
    In the WHEN-BUTTON-PRESSED-Trigger enter :
    DECLARE
        v_block_def_where         VARCHAR2(255)     := '1 = 1';
    BEGIN
        v_block_def_where := v_block_def_where || ' AND NAME_OF_YOUR_TABLE_COLUMN LIKE ''' || '%' || :NAME_OF_YOUR_BLOCK.SEARCH_ITEM || '%' ||  '''';
        SET_BLOCK_PROPERTY('NAME_OF_YOUR_BLOCK', DEFAULT_WHERE, v_block_def_where);
        GO_BLOCK('NAME_OF_YOUR_BLOCK');
        EXECUTE_QUERY;
    END;

  • Include dynamic conditions in the where clause

    Hi All,
    I have an requirement where i need to dynamically include the conditions in the where clause based on the bind variable.
    My condition is like this.
    SELECT f.scheduled_date, a.bld_id, a.room_id, a.cage_id, f.test_num
    FROM feeding_test_results f,
    v_onl_gf_anmls a
    WHERE f.sak_feeding_test_res > 5000000
    AND f.anml_id(+) = a.anml_id
    AND f.bld_id = 'A5'
    AND f.room_id > 0
    AND f.cage_id > '0'
    case when :check_value = 1 Then
    AND scheduled_date <= '16-Apr-2009'
    AND scheduled_date >= '06-Apr-2009'
    Else
    AND scheduled_date = '16-Apr-2009'
    End
    AND f.feeding_status <> 'X') f
    Kindly anyone help me how to acheive this.
    Thanks & Regards,
    P. Gayathri Devi

    michaels2 wrote:
    and scheduled_date <= case when :check_value = 1 then date '2009-04-16' end
    and scheduled_date >= case when :check_value = 1 then date '2009-04-06' end
    and scheduled_date = case when not :check_value = 1 then date '2009-04-16' end
    Hmmm, you may want some NVL's around those case statements such as..
           and scheduled_date <= NVL(case when :check_value = 1 then date '2009-04-16' end,scheduled_date)
           and scheduled_date >= NVL(case when :check_value = 1 then date '2009-04-06' end,scheduled_date)
           and scheduled_date = NVL(case when not :check_value = 1 then date '2009-04-16' end,,scheduled_date)or some such thing. Otherwise the comparisons with Null will just cause it all to fail.

  • How to use multiple selection parameters in the data model

    Hi, after have looked all the previous threads about how to use multiple selection parameters , I still have a problem;
    I'm using Oracle BI Publisher 10.1.3.3.2 and I'm tried to define more than one multiple selection parameters inside the data template;
    Inside a simple SQL queries they work perfectly....but inside the data template I have errors.
    My data template is the following (it's very simple...I am just testing how the parameters work):
    <dataTemplate name="Test" defaultPackage="bip_departments_2_parameters">
    <parameters>
    <parameter name="p_dep_2_param" include_in_output="false" datatype="character"/>
    <parameter name="p_loc_1_param" include_in_output="false" datatype="character"/>
    </parameters>
    <dataTrigger name="beforeReport" source="bip_departments_2_parameters.beforeReportTrigger"/>
    <dataQuery>
    <sqlStatement name="Q2">
    <![CDATA[
    select deptno, dname,loc
    from dept
    &p_where_clause
    ]]>
    </sqlStatement>
    </dataQuery>
    <dataStructure>
    <group name="G_DEPT" source="Q2">
    <element name="deptno" value="deptno"/>
    <element name="dname" value="dname"/>
    <element name="loc" value="loc"/>
    </group>
    </dataStructure>
    </dataTemplate>
    The 2 parameters are based on these LOV:
    1) select distinct dname from dept (p_dep_2_param)
    2) select distinct loc from dept (p_loc_1_param)
    and both of them have checked the "Multiple selection" and "Can select all" boxes
    The package I created, in order to use the lexical refence is:
    CREATE OR REPLACE package SCOTT.bip_departments_2_parameters
    as
    p_dep_2_param varchar2(14);
    p_loc_1_param varchar2(20);
    p_where_clause varchar2(100);
    function beforereporttrigger
    return boolean;
    end bip_departments_2_parameters;
    CREATE OR REPLACE package body SCOTT.bip_departments_2_parameters
    as
    function beforereporttrigger
    return boolean
    is
    l_return boolean := true;
    begin
    if (p_dep_2_param is not null) --and (p_loc_1_param is not null)
    then
    p_where_clause := 'where (dname in (' || replace (p_dep_1_param, '''') || ') and loc in (' || replace (p_loc_1_param, '''') || '))';
    else
    p_where_clause := 'where 1=1';
    end if;
    return (l_return);
    end beforereporttrigger;
    end bip_departments_2_parameters;
    As you see, I tried to have only one p_where_clause (with more than one parameter inside)....but it doesn't work...
    Using only the first parameter (based on deptno (which is number), the p_where_clause is: p_where_clause := 'where (deptno in (' || replace (p_dep_2_param, '''') || '))';
    it works perfectly....
    Now I don't know if the problem is the datatype, but I noticed that with a single parameter (deptno is number), the lexical refence (inside the data template) works.....with a varchar parameter it doesn't work....
    So my questions are these:
    1) how can I define the p_where_clause (inside the package) with a single varchar parameter (for example, the department location name)
    2) how can I define the p_where_clause using more than one parameter (for example, the department location name and the department name) not number.
    Thanks in advance for any suggestion
    Alex

    Alex,
    the missing thing in your example is the fact, that if only one value is selected, the parameter has exact this value like BOSTON. If you choose more than one value, the parameter includes the *'*, so that it looks like *'BOSTON','NEW YORK'*. So you need to check in the package, if there's a *,* in the parameter or not. If yes there's more than one value, if not it's only one value or it's null.
    So change your package to (you need to expand your variables)
    create or replace package bip_departments_2_parameters
    as
    p_dep_2_param varchar2(1000);
    p_loc_1_param varchar2(1000);
    p_where_clause varchar2(1000);
    function beforereporttrigger
    return boolean;
    end bip_departments_2_parameters;
    create or replace package body bip_departments_2_parameters
    as
    function beforereporttrigger
    return boolean
    is
    l_return boolean := true;
    begin
    p_where_clause := ' ';
    if p_dep_2_param is not null then
    if instr(p_dep_2_param,',')>0 then
    p_where_clause := 'WHERE DNAME in ('||p_dep_2_param||')';
    else
    p_where_clause := 'WHERE DNAME = '''||p_dep_2_param||'''';
    end if;
    if p_loc_1_param is not null then
    if instr(p_loc_1_param,',')>0 then
    p_where_clause := p_where_clause || ' AND LOC IN ('||p_loc_1_param||')';
    else
    p_where_clause := p_where_clause || ' AND LOC = '''||p_loc_1_param||'''';
    end if;
    end if;
    else
    if p_loc_1_param is not null then
    if instr(p_loc_1_param,',')>0 then
    p_where_clause := p_where_clause || 'WHERE LOC in ('||p_loc_1_param||')';
    else
    p_where_clause := p_where_clause || 'WHERE LOC = '''||p_loc_1_param||'''';
    end if;
    end if;
    end if;
    return (l_return);
    end beforereporttrigger;
    end bip_departments_2_parameters;
    I've written a similar example at http://www.oracle.com/global/de/community/bip/tipps/Dynamische_Queries/index.html ... but it's in german.
    Regards
    Rainer

  • PL/SQL: how to use in parameter in select sql where clause

    Hi
    in a procedure, I need to apply 'in parameter' in 'where clause' along with other table fields. Purpose is to create dynamic select querry with multiple conditions.
    select count(*) from table xx
    where y_code=2008 and v_type in ('SI', 'TI', 'DI') ;
    my requirement is replace 'and v_type in ('SI', 'TI', 'DI')' with in parameter. pls note in paramter may contain null value.
    Regards

    ... e.g. why on earth do you want to pass in a string to be appended to the WHERE clause of an SQL.I second that and I strongly advice NOT to do it. If you really want to do it, then come back and show us, how you would prevent SQL injection. This approach is too dangerous (and too complex) IMHO.
    Do it straight forward as in the article of Tom Kyte (link in the post of BluShadow above)

  • How to use a lexical variable in a WHERE clause and as a function argument.

    Hello,
    My report has a lexical variable which has values like 'and id in (1,3,4)'. I want to use this variable in two separate queries. In the first, it is used in the WHERE clause, something like:
    .. where date is not null &var;
    In the second query, the variable is used in a function call, something like:
    select * from table (my_function(&var));
    The trouble is that the first query works when the value of the variable is unquoted, but for the second query the value should be quoted.
    Does anyone have an idea how I could solve this problem?
    Thanks in advance,
    Frans
    Message was edited by:
    fransie

    http://tkyte.blogspot.com/2006/06/varying-in-lists.html
    Presents many options.

  • Function-based Index and an OR-condition in the WHERE-clause

    We have some problems with functin-based indexes and
    the or-condition in a where-clause.
    (We use oracle 8i (8.1.7))
    create table TPERSON(ID number(10),NAME varchar2(20),...);
    create index I_NORMAL_TPERSON_NAME on TPERSON(NAME);
    create index I_FUNCTION_TPERSON_NAME on TPERSON(UPPER(NAME));
    The following two statements run very fast on a large table
    and the execution-plan asure the usage of the indexes
    (-while the session is appropriate configured and the table is analyzed):
    1)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%';
    2)     select count(ID) from TPERSON where NAME like 'Mil%' or (3=5);
    In particular we see that a normal index is used while the where-clause contains
    an OR-CONDITION.
    But if we try the similarly select-statement
    3)     select count(ID) FROM TPERSON where upper(NAME) like 'MIL%' or (3=5);
    the CBO will not use the function-index.
    (This behavior we only expect with views but not with indexes.)
    We ask for an advice like an hint, which enable the CBO-usage
    of function-based indexes in connection with OR.
    This problem seems to be artificial because it contains this dummy logic:
         or (3=5).
    This steams from an prepared statement, where this kind of boolean
    flag reduce the amount of different select-statements needed for
    covering the hole business-logic, while using bind-variables for the
    concrete query-parameters.
    A more realistic (still boild down) version of our prepared select-statement run in
    SQL Plus:
    define x_name = 'MIL%';
    define x_firstname = '';
    select * FROM TPERSON
    where (upper(NAME) like '&x_name' or ( '&x_name' = ''))
    and (upper(FIRSTNAME) like '&x_firstname' or ('&x_firstname' = ''))
    and ...;
    In particular we dont refernce the tablecolumn , but the QUERY-Parameter
    yield the second boolean value in the or-condition.
    The problem is that this condition ('&x_name' = '') dont use any index.
    thanks a lot for spending your time with this problem

    Try
    SELECT /*+ RULE */
    as your hint. I don't have the book with me, but this last weekend I read a section about your very problem. The book was a Oracle Press gold cover about Oracle 8i Performance tuning. If you e-mail me I can quote you the chapter when I get home Friday.

  • How to use floor(to_number(substr x))) in where clause???

    Hi,
    I have a column doc_id which value like abcd.01.023. If I
    select floor(to_number(substr(doc_id, instr(doc_id, '.', 1)+1, instr(doc_id, '.', 1)+1 )))
    it works,
    but get ORA-01722: invalid number if I use in where clause like:
    Where floor(to_number(substr(doc_id, instr(doc_id, '.', 1)+1, instr(doc_id, '.', 1)+1 ))) =0
    Could you tell me how to fix?
    Thansk

    My guess is that you didn't process the same rows with each query. Maybe you have some where conditions on the 'select' query that filters out the offending rows. If the doc_id value could not be converted to a number is should raise the error in either case.
    Besides that, your substring looks wrong to me. Why take "instr(doc_id, '.', 1)+1" characters? Why not just:
    floor(substr(doc_id, instr(doc_id, '.') + 1))
    Even then, the portion after the first '.' must be a valid number.
    Richard

  • UPDATE using a second table for the Where Clause

    Hi There,
    Hoep someone can help me!
    I am attempting to update a field in Tbl.1 to a known value. However, i want to use another table to specify WHICH records to update.
    in this case i want to use table early_provider to obtain the value 'HCR' then pass that to the UPDATE clause in order to SET early_provisions.type_name = 'HOMC'
    I hope this makes sense.
    UPDATE EARLY_PROVISIONS eps
    SET TYPE_NAME = (SELECT *
    FROM EARLY_PROVIDER ep
    WHERE PROVIDER_TYPE = 'HCR'
    WHERE EP.PROVIDER_ID = EPS.PROVIDER_ID);
    I need to be able to include the field value 'HOMC in this statement but am not sure how, or if i am barking up the wrong tree.
    Much appreciated in advance
    PFG

    PFGMcAvoy wrote:
    Karthick_Arp
    Thanks. this seems to only update 15 rows of which already exist in the table early_provisions and filed type_name!
    I should be selecting about 200 recordsd from early_provider that have the provider_type = 'HCR'
    ??I don't know your data. So i cant answer that. But for what you asked i think thats the correct UPDATE statement. So i think you have to investigate your data to find what is going on.

  • How to use a purchase condition in the sales order

    Hello,
    Customer would like to have a purchase "day-price" appearing in the pricing of the sales order. 
    I would suggest to write abap code (reading the correct PU condition record) in a condition base value routine that would be added in the customizing pricing procedure at SD side.
    Is there any "more standard" solution for this ? 
    Thanks,

    Hello,
    Here is the case in more detail :
    This question concerns a product that is just purchased, stored, and sold.  The purchase-price is based on a "day-price" that is maintained in a purchase condition record on a daily basis.  The sales-price should be that daily price with a markup in %. 
    So, in the sales order, this purchase condition record should be picked up with the material and the pricing date as key.  From that base price, a markup can be calculated in sales pricing. 
    I would suggest to use the field "condition base value" in the setup of the sales pricing procedure (Ref to IMG sales and distribution, pricing control, define and assign pricing procedures).  In that field a new routine could be entered that (with a select or function or Bapi) picks up the purchase condition record-value. 
    I would like to know if this would be a "correct" way of solving this requirement,  if there is no "more standard" solution,  if anyone has experience with a similar requirement and how you solved it ?
    Thanks,

  • Using a variable to vary the WHERE clause in a statement

    I have an int column that has values >= 0.
    Depending on a variable I want to select all the rows of the table or only the rows where the int column is 0.
    How do I do this?
    Your help would be much appreciated.
    Thanking you in anticipation.
    Roger
    rogerwithnell

    Please post DDL, so that people do not have to guess what the keys, constraints, Declarative Referential Integrity, data types, etc. in your schema are. Learn how to follow ISO-11179 data element naming conventions and formatting rules. Temporal data should
    use ISO-8601 formats. Code should be in Standard SQL as much as possible and not local dialect. 
    This is minimal polite behavior on SQL forums. Why do you think "a variable" and "the integer column" are precise clear specs? I hate to tell you but zero is a integer. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

  • How can define an outer join in the where clause of a flowr statement?

    Hi- In the sample below I'm joining two views based on username but in this case what I really want to use is an outer join instead. What is the syntax for that? I tried the (+) notation but that didn't seem to work..
    CREATE OR REPLACE PROCEDURE proc_ctsi_all is
    XMLdoc XMLType;
    BEGIN
    DBMS_XDB.deleteResource('/public/CTSI/ctsi_all_rpt1.xml',1);
    SELECT XMLQuery(
    '<Progress_Report>
    <Personnel_Roster>
    {for $c in ora:view("CTSI_INVEST_NONPHS_SOURCE_V"),
    $cphs in ora:view("CTSI_INVEST_PHS_SOURCE_V")
      let $username  := $c/ROW/COMMONS_USERNAME/text(),
    $expertise  := $c/ROW/AREA_OF_EXPERTISE/text(),
    $phsorg  := $cphs/ROW/PHS_ORGANIZATION/text(),
    $activitycode  := $cphs/ROW/ACTIVITY_CODE/text(),
    $username2  := $cphs/ROW/COMMONS_USERNAME/text()
    where $username eq $username2
         return
      <Investigator>
       <Commons_Username>{$username}</Commons_Username>
    <Area_of_Expertise>{$expertise}</Area_of_Expertise>
    <Federal_PHS_Funding>
    <Organization>{$phsorg}</Organization>
    <Activity_Code>{$activitycode}</Activity_Code>
    <Six_Digit_Grant_Number>{$grantnumber}</Six_Digit_Grant_Number>
    </Federal_PHS_Funding>
    </Investigator>}
    </Personnel_Roster>
    </Progress_Report>'
    RETURNING CONTENT) INTO XMLdoc FROM DUAL;
    IF(DBMS_XDB.CREATERESOURCE('/public/CTSI/ctsi_all_rpt1.xml', XMLdoc)) THEN
    DBMS_OUTPUT.PUT_LINE('Resource is created');
    ELSE
    DBMS_OUTPUT.PUT_LINE('Cannot create resource');
    END IF;
    COMMIT;
    END;
    /

    What you could do is use query within an XMLTable syntax. Via the COLUMNS parameter you then pass the "column" as XMLType to the following XMLtable statement.
    little bit like the following
    select hdjfdf
    from xmltable
       ({xquery}
        PASSING
        COLUMNS xmlfrag xmltype path 'xxx'
       ) a
    ,  xmltable
       ({the other stuff you need}
        PASSING a.xmlfrag
       ...etc
      ...etc                 I guess something simular can be done via XQuery straight away as well

  • Should I use And or OR in the Where Clause?

    2 Databases have been merged, and in the purge some data was omitted, so I am running clean-up.  Now I need a query to show me if item1 is null, then check olditem1 if both fields are null then ignore the record completely.  But If either field
    has a value I need it returned.  So 1st check item1 if that field is not null, then return the record, if item1 is null, check olditem1 if that field is not null then return the record.  If both fileds are null, ignore the record and let's check
    the next one.
    Sample Data;
    Select
    Test.StaffIDID,
    Test.purchasedfrom,
    Test.date,
    case when Test.item1 is null then Test.olditem1 else null end as [1st Item],
    case when Test.item2 is null then Test.olditem2 else null end as [2nd Item],
    From internetsales Test
    CREATE TABLE Test
    StaffID INT NOT NULL PRIMARY KEY,
    purchasedfrom NVARCHAR(30) NOT NULL,
    date DateTime NOT NULL,
    item1 NVARCHAR(50),
    item2 NVARCHAR(50),
    olditem1 NVARCHAR(50),
    olditem2 NVARCHAR(50)
    INSERT Test VALUES
    (2, 'web1', '2010-01-02', 'stereo', 'NULL', 'NULL', 'NULL'),
    (3, 'web3', '2011-02-15', 'NULL', 'microphone', 'NULL', 'NULL'),
    (4, 'web14', '2014-02-21', 'NULL', 'NULL', 'NULL', 'headset'),
    (5, 'web81', '2015-01-01', 'NULL', 'NULL', 'MP3 Player', 'NULL');
    (6, 'web18', '2011-01-01', 'Dryer', 'NULL', 'MP3 Player', 'NULL');
    (7, 'web8', '2009-01-01', 'NULL', 'NULL', 'Stove', ''NULL);
    (8, 'web828', '2002-01-01', 'NULL', 'NULL', 'NULL', 'USB HUB');
    (9, 'web88', '2007-01-01', 'Refrigerator', 'NULL', 'NULL', 'NULL');
    (10, 'web89', '2009-01-01', 'NULL', 'NULL', 'NULL', 'NULL');
    Desired returned result sets would be StaffIDs: 2,5,6,7,9 -- as they have a value for item1 or olditem1

    Looks like you totally ignored my answer :-(
    well... you have your reason probably...
    You do realize that I gave you the answer from the start?!?
    Hi,
    your sample data do not include any NULL value. Blank string is not NULL.
    Please clarify your question and give us the result that you want to get, according to your sample data.
    * if your data is NULL and not empty string that you can use COALESCE(item1, olditem1,'') in order to get the first value that is not NULL. if both
    NULL then it will return blank string as this is the first value that is not null
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]
    Using nested IIF can be done directly with the
    COALESCE function.
    The execution plan is the same, but the code is much cleaner and easier to write or read.
    There is a reason for this function.
    * In your current needs there are only 2 nested IIF, but you should know about COALESCE function! Once you get more complex situation you will be able to get a solution much faster and probably without any mistake on the first try.
    try to use 5 nested IIF... using COALESCE  this is simple as 2 or 10... all you need is to write all the values and the function will return the first that is not NULL
    Any way, I hope this is useful for people that will come to this thread in future :-)
    -- SOLUTION 1: using nested IIF
    SELECT StaffID, purchasedfrom, date,
    IIF(ITEM1 IS NOT NULL, ITEM1, IIF(OLDITEM1 IS NOT NULL, OLDITEM1,NULL)) AS [1ST ITEM],
    IIF(ITEM2 IS NOT NULL, ITEM2,IIF(OLDITEM2 IS NOT NULL, OLDITEM2,NULL)) AS [2ND ITEM]
    FROM Test
    -- solution 2: using COALESCE
    SELECT
    StaffID, purchasedfrom, date,
    COALESCE(ITEM1, OLDITEM1) AS [1ST ITEM],
    COALESCE(ITEM2, OLDITEM2) AS [2ND ITEM]
    FROM Test
    -- Whish solution look simpler to read, write or use?
    -- The execution plan is the same, but it is always good idea to make sure if you are not sure :-)
    I hope this is useful :-)
      Ronen Ariely
     [Personal Site]    [Blog]    [Facebook]

  • Forcing Index use with UPPER or LOWER in the WHERE clause.

    Does anyone know how to force Oracle to use an index/Key when using UPPER or LOWER in the WHERE clause?

    You have to create a function index. Check your documentation on it.

  • Query Tuning - using CASE statement in the WHERE clause

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

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

Maybe you are looking for

  • How can I connect my Mac laptop to display on my imac

    I just bout an imac with a 27" display. I would like to use the display for my macbook air - how do I connect the two just to project the AIR on my imac.

  • User decision history report, workflow summary log

    Hello SAP Workflow community, In our project there is a task to implement User Decision history/log management. I want to get programmatically (via ABAP, in order to be able to store this data in DB too) the history all user decisions (statuses of al

  • Duplicate email

    The new thing with this email, is every email in my in box is duplicated.  I have the first 5 or 6 emails, and right underneath that I have the same 5 or 6 emails again. I tried deleting them and then did delete,, but the next time I went to my in bo

  • Elements 10 won't recognize my printer

    I have printed many times with the current printer, Epson XP 810, and recently paused it in the middle of a job.  Now I get the error message that I have to install a printer. I changed the printer name to a shorter one and I still get the message. T

  • When in mail, opening it in Safari, it locks up.  Why is this happening

    When in mail, opening it up in Safari,, it locks up.  Why is this happening?  The only way to unlock is to go to Settings>mail> load remote images and turn off.  Then turn off wi-fi and turn it back on.  Then go to mail and it is back to normal.  Why