How to rewrite a query using an or condition?

my query has a condition in the where caluse which has a OR part. because of the OR part the query cost increases.
is ther any way to rewrite the OR part apart from using an UNION operator.
select * from table1 a,table2 b where
a.field1 = 'CONSTANT'
and
a.field2= b.field2
and (a.field3 = 'input value' or a.field4 = 'input value')

Just a suggestion(May be a blunder)
select * from table1 a,table2 b where
a.field1 = 'CONSTANT'
and
a.field2= b.field2
and DECODE('INPUT',a.field3,'x',a.field4,'x','y')  = 'x'
Message was edited by:
        jeneesh                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

Similar Messages

  • How can rewrite the Query using Analytical functions ?

    Hi,
    I have the SQL script as shown below ,
    SELECT cd.cardid, cd.cardno,TT.TRANSACTIONTYPECODE,TT.TRANSACTIONTYPEDESC DESCRIPTION,
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'LOAD_ACH'
    THEN th.transactionamount
    END, 0)
    ) AS load_ach,
    SUM
    (NVL (CASE tt.transactiontypecode
    WHEN 'FUND_TRANSFER_RECEIVED'
    THEN th.transactionamount
    END,
    0
    ) AS Transfersin,
    ( SUM (NVL (CASE tt.transactiontypecode
    WHEN 'FTRNS'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'SEND_MONEY'
    THEN th.transactionamount
    END, 0)
    )) AS Transferout,
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_ACH'
    THEN th.transactionamount
    END, 0)
    ) AS withdrawal_ach,
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_CHECK'
    THEN th.transactionamount
    END, 0)
    ) AS withdrawal_check,
    ( SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_CHECK_FEE'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'REJECTED_ACH_LOAD_FEE'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_ACH_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_CHECK_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM
    (NVL (CASE tt.transactiontypecode
    WHEN 'WITHDRAWAL_CHECK_FEE_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM
    (NVL (CASE tt.transactiontypecode
    WHEN 'REJECTED_ACH_LOAD_FEE_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'OVERDRAFT_FEE_REV'
    THEN th.transactionamount
    END, 0)
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'STOP_CHECK_FEE_REV'
    THEN th.transactionamount
    END,
    0
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'LOAD_ACH_REV'
    THEN th.transactionamount
    END, 0)
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'OVERDRAFT_FEE'
    THEN th.transactionamount
    END, 0)
    ) +
    SUM (NVL (CASE tt.transactiontypecode
    WHEN 'STOP_CHECK_FEE'
    THEN th.transactionamount
    END, 0)
    )) AS Fee,
    th.transactiondatetime
    FROM carddetail cd,
    transactionhistory th,
    transactiontype tt,
    (SELECT rmx_a.cardid, rmx_a.endingbalance prev_balance, rmx_a.NUMBEROFDAYS
    FROM rmxactbalreport rmx_a,
    (SELECT cardid, MAX (reportdate) reportdate
    FROM rmxactbalreport
    GROUP BY cardid) rmx_b
    WHERE rmx_a.cardid = rmx_b.cardid AND rmx_a.reportdate = rmx_b.reportdate) a
    WHERE th.transactiontypeid = tt.transactiontypeid
    AND cd.cardid = th.cardid
    AND cd.cardtype = 'P'
    AND cd.cardid = a.cardid (+)
    AND CD.CARDNO = '7116734387812758335'
    --AND TT.TRANSACTIONTYPECODE = 'FUND_TRANSFER_RECEIVED'
    GROUP BY cd.cardid, cd.cardno, numberofdays,th.transactiondatetime,tt.transactiontypecode,TT.TRANSACTIONTYPEDESC
    Ouput of the above query is :
    CARDID     CARDNO     TRANSACTIONTYPECODE     DESCRIPTION     LOAD_ACH     TRANSFERSIN     TRANSFEROUT     WITHDRAWAL_ACH     WITHDRAWAL_CHECK     FEE     TRANSACTIONDATETIME
    6005     7116734387812758335     FUND_TRANSFER_RECEIVED     Fund Transfer Received     0     3.75     0     0     0     0     21/09/2007 11:15:38 AM
    6005     7116734387812758335     FUND_TRANSFER_RECEIVED     Fund Transfer Received     0     272     0     0     0     0     05/10/2007 9:12:37 AM
    6005     7116734387812758335     WITHDRAWAL_ACH     Withdraw Funds via ACH     0     0     0     300     0     0     24/10/2007 3:43:54 PM
    6005     7116734387812758335     SEND_MONEY     Fund Transfer Sent     0     0     1     0     0     0     19/09/2007 1:17:48 PM
    6005     7116734387812758335     FUND_TRANSFER_RECEIVED     Fund Transfer Received     0     1     0     0     0     0     18/09/2007 7:25:23 PM
    6005     7116734387812758335     LOAD_ACH     Prepaid Deposit via ACH     300     0     0     0     0     0     02/10/2007 3:00:00 AM
    I want the output like for Load_ACH there should be one record etc.,
    Can any one help me , how can i rewrite the above query using analytical functions .,
    Sekhar

    Not sure of your requirements but this mayhelp reduce your code;
    <untested>
    SUM (
       CASE
       WHEN tt.transactiontypecode IN
          ('WITHDRAWAL_CHECK_FEE', 'REJECTED_ACH_LOAD_FEE', 'WITHDRAWAL_ACH_REV', 'WITHDRAWAL_CHECK_REV',
           'WITHDRAWAL_CHECK_FEE_REV', 'REJECTED_ACH_LOAD_FEE_REV', 'OVERDRAFT_FEE_REV','STOP_CHECK_FEE_REV',
           'LOAD_ACH_REV', 'OVERDRAFT_FEE', 'STOP_CHECK_FEE')
       THEN th.transactionamount
       ELSE 0) feeAlso, you might want to edit your post and use &#91;pre&#93; and &#91;/pre&#93; tags around your code for formatting.

  • How to rewrite this query

    How can i rewrite this query so it uses less inner joins (it causes my temp space to explode :) )
    ( SELECT Waardes.*, Tellers.Nr_Dataitems, Tellers.Nr_Details FROM
    ( SELECT extractvalue(Value(el_node), 'Node/Id') node,
    extractvalue(Value(el_dataitem), 'Detail/Title') Node_Title,
    extractvalue(Value(el_dataitem), 'Detail/Value') Node_Value
    FROM PHILIPS_XML x,
    TABLE (xmlsequence (extract (value(x), '/Tree/Node'))) el_node,
    TABLE (xmlsequence (extract (value(el_node),
    'Node/DataItems/DataItem/DetailSet/Detail'))) el_dataitem
    ) Waardes
    INNER JOIN
    SELECT A.Node, A.Nr_Dataitems, B.Nr_details FROM
    SELECT extractvalue(Value(el_node), 'Node/Id') node,
    count(extract(Value(aaa), 'DataItem')) Nr_Dataitems
    FROM PHILIPS_XML x,
    TABLE (xmlsequence (extract (value(x), '/Tree/Node'))) el_node,
    TABLE (xmlsequence (extract (value(el_node),
    'Node/DataItems/DataItem'))) aaa
    GROUP BY extractvalue(Value(el_node), 'Node/Id')
    ) A
    INNER JOIN
    SELECT extractvalue(Value(el_node), 'Node/Id') node,
    count(extract(Value(bbb), 'Detail')) Nr_details
    FROM PHILIPS_XML x,
    TABLE (xmlsequence (extract (value(x), '/Tree/Node'))) el_node,
    TABLE (xmlsequence (extract (value(el_node),
    'Node/DataItems/DataItem'))) aaa,
    TABLE (xmlsequence (extract (value(aaa),
    'DataItem/DetailSet/Detail' ))) bbb
    GROUP BY extractvalue(Value(el_node), 'Node/Id')
    ) B
    on A.node = B.NODE
    ) Tellers
    ON Waardes.NODE = Tellers.NODE )

    1st Make sure all paths are absolute (start with '/', not just the node name).
    Which release are you using.. Is the document based on an XMLSchema, if so, what annotations were used when registered the XML Schema ?. What does the explain plan look like...

  • How to make dynamic query using DBMS_SQL variable column names

    First of all i will show a working example of what i intend to do with "EXECUTE IMMEDIATE":
    (EXECUTE IMMEDIATE has 32654 Bytes limit, which isn't enough for me so i'm exploring other methods such as DBMS_SQL)
    -------------------------------------------------CODE-----------------------------------
    create or replace PROCEDURE get_dinamic_query_content
    (query_sql IN VARCHAR2, --any valid sql query ('SELECT name, age FROM table') 
    list_fields IN VARCHAR2) --list of the columns name belonging to the query (  arr_list(1):='name';   arr_list(2):='age';
    -- FOR k IN 1..arr_list.count LOOP
    -- list_fields := list_fields || '||content.'||arr_list(k)||'||'||'''~cs~'''; )
    AS
    sql_stmt varchar (30000);
    BEGIN
                   sql_stmt :=
    'DECLARE
         counter NUMBER:=0;     
    auxcontent VARCHAR2(30000);     
         CURSOR content_cursor IS '|| query_sql ||';
         content content_cursor%rowtype;     
         Begin
              open content_cursor;
              loop
                   fetch content_cursor into content;
                   exit when content_cursor%notfound;
                   begin                              
                        auxcontent := auxcontent || '||list_fields||';                    
                   end;
                   counter:=counter+1;     
              end loop;
              close content_cursor;
              htp.prn(auxcontent);
         END;';
    EXECUTE IMMEDIATE sql_stmt;
    END;
    -------------------------------------------------CODE-----------------------------------
    I'm attepting to use DBMS_SQL to perform similar instructions.
    Is it possible?

    Hi Pedro
    You need to use DBMS_SQL here because you don't know how many columns your query is going to have before runtime. There are functions in DBMS_SQL to get information about the columns in your query - all this does is get the name.
    SQL&gt; CREATE OR REPLACE PROCEDURE get_query_cols(query_in IN VARCHAR2) AS
    2 cur PLS_INTEGER;
    3 numcols NUMBER;
    4 col_desc_table dbms_sql.desc_tab;
    5 BEGIN
    6 cur := dbms_sql.open_cursor;
    7 dbms_sql.parse(cur
    8 ,query_in
    9 ,dbms_sql.native);
    10 dbms_sql.describe_columns(cur
    11 ,numcols
    12 ,col_desc_table);
    13 FOR ix IN col_desc_table.FIRST .. col_desc_table.LAST LOOP
    14 dbms_output.put_line('Column ' || ix || ' is ' ||
    15 col_desc_table(ix).col_name);
    16 END LOOP;
    17 dbms_sql.close_cursor(cur);
    18 END;
    19 /
    Procedure created.
    SQL&gt; exec get_query_cols('SELECT * FROM DUAL');
    Column 1 is DUMMY
    PL/SQL procedure successfully completed.
    SQL&gt; exec get_query_cols('SELECT table_name, num_rows FROM user_tables');
    Column 1 is TABLE_NAME
    Column 2 is NUM_ROWS
    PL/SQL procedure successfully completed.
    SQL&gt; exec get_query_cols('SELECT column_name, data_type, low_value, high_value FROM user_tab_cols');
    Column 1 is COLUMN_NAME
    Column 2 is DATA_TYPE
    Column 3 is LOW_VALUE
    Column 4 is HIGH_VALUE
    PL/SQL procedure successfully completed.I've just written this as a procedure that prints out the column names using dbms_output - I guess you're going to do something different with the result - maybe returning a collection, which you'll then parse through in Apex and print the output on the screen - this is just to illustrate the use of dbms_sql.
    best regards
    Andrew
    UK

  • How to find sql query using sqlid

    Hi
    I am not aware of that sqlid .DBA is saying a particular sqlid is making problem .how to find the particular sql query using sql_id ?

    Are you aware of modplsql when i executed the query the result is like
    DECLARE
       rc__             NUMBER;
       simple_list__    OWA_UTIL.vc_arr;
       complex_list__   OWA_UTIL.vc_arr;
    BEGIN
       OWA.init_cgi_env (:n__, :nm__, :v__);
       HTP.htbuf_len := 84;
       NULL;
       NULL;
       simple_list__ (1) := 'sys.%';
       simple_list__ (2) := 'dbms\_%';
       simple_list__ (3) := 'utl\_%';
       simple_list__ (4) := 'owa\_%';
       simple_list__ (5) := 'owa.%';
       simple_list__ (6) := 'htp.%';
       simple_list__ (7) := 'htf.%';
       simple_list__ (8) := 'wpg_docload.%';
       IF ((owa_match.match_pattern ('Oly_browse.oly_pattern ',
                                     simple_list__,
                                     complex_list__,
                                     TRUE
       THEN
          rc__ := 2;
       ELSE
          NULL;
          NULL;
         oly_browse.oly_pattern (search_phrase      => :search_phrase,           --Oly_browse.oly_pattern is package name
                                btn                => :btn,
                                p_qual             => :p_qual,
                                p_bcat             => :p_bcat,
                                p_stdy             => :p_stdy,
                                p_bloc             => :p_bloc,
                                z                  => :z
          IF (WPG_DOCLOAD.is_file_download)
          THEN
             rc__ := 1;
             WPG_DOCLOAD.get_download_file (:doc_info);
             NULL;
             NULL;
             NULL;
             COMMIT;
          ELSE
             rc__ := 0;
             NULL;
             NULL;
             NULL;
             COMMIT;
             OWA.get_page (:data__, :ndata__);
          END IF;
       END IF;
       :rc__ := rc__;
    END; Edited by: vishnu prakash on Sep 8, 2010 10:16 PM

  • How to write the query using Index

    Hi All,
    I have to fetch the records from Database table using Index, how can i write the query using Index. Can any body plz send me the sample code.
    Help Me,
    Balu.

    Hi,
    See the below Example.
    select * from vbak up to 100 rows
    into table t_vbak
    where vbeln > v_vbeln.
    sort t_vbak by vbeln descending.
    read table t_vbak index 1.
    Regards,
    Ram
    Pls reward points if helpful.

  • How to rewrite this query without sub query please help me

    Hello All Good Evening,
    Could you please help me with this query, how can i write this query without sub query, or how can write this query another ways
    please help me
    select planno, status1, count(*) Counts from
    select a.ValetNO PlanNo  ,
    case 
         when JoinCode in ('00', '01', '02') then 'Actcess'
         when JoinCode in ('20', '21', '22', '23','38', '39') then
         'Secured' else 'Other' end Status1 ---, COUNT (*)
       from  dbo.ppt a(NOLOCK)  left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO  = b.ValetNO
    --group by a.ValetNO
      a group by planno, status1
    order by 2
    Thank you in Advance
    Milan

    Whats your objective here? Sorry, am not able to understand the reason for this change. 
    Try the below:(Not tested)
    ;With cte
    As
    select a.ValetNO PlanNo ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end Status1 ---, COUNT (*)
    from dbo.ppt a(NOLOCK) left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO = b.ValetNO
    select planno, status1, count(*) Counts from cte
    a group by planno, status1
    order by 2
    Even below:
    select a.ValetNO PlanNo ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end Status1 , COUNT (1)
    from dbo.ppt a(NOLOCK) left join dbo.acts b on a.P_ID = b.P_ID and a.ValetNO = b.ValetNO
    Group by a.ValetNO ,
    case
    when JoinCode in ('00', '01', '02') then 'Actcess'
    when JoinCode in ('20', '21', '22', '23','38', '39') then
    'Secured' else 'Other' end

  • How to write this query using correlation subquery or non exists clause

    -- Tables description.
    --step-1- 4 employees present in EMP table.
    --step-2- each employee having 1 country_no in EMP_DOCS table.3 employees having same country_no(i.e emp's 1,2,3)
    --step-3- 1 emp document can have multiple items.In this case each employee having one each in the EMP_ITEMS table.
    --step-4- 1 EMPLOYEE  can have Multiple Documents so we have a relation between EMP_ITEMS and DOCUMENT_ITEMS.whatever items present in EMP_ITEMS those items will be inserted into DOCUMENT_ITEMS.so we have a item-item relation.
    --so we stored EMP_ITEMS id in EMP_ITEMS_REF_ID_1 of DOCUMENT_ITEMS table.
    -- step-5- DOCUMENT-INVOICE has 1-1 relation once invoice is created we stored invoice id in DOCUMENT table.
    --This is the requirement.Let's say in this example 3 employees are using same country_no and 4th employee is using another country_no
    --which is not used by other 3 employees.
    --Condtion-1:
    --if all of the employees have created INVOICE which is using same country_no of different country_no then the query should display all records.
    --Condition-2:
    --if any one of the employee not created INVOICE which is using same country_no of other employees then remaining employees also should not come in the query
    -- even though invoice is created by other employees.
    --Condition-3:
    --if any one of the employee not created even DOCUMENT  which is using same country_no of other employees then remaining employees also should not come in the query
    -- even though invoice is created by other employees.
    I hope I explain the conditions clearly.if you understand well by looking at the data i posted below may i know what is the final result should be displayed?
    create table EMP
      ID       NUMBER not null,
      TYPE     VARCHAR2(1)
    alter table EMP
      add constraint ID primary key (ID);
    create table EMP_DOCS
      ID         NUMBER not null,
      EMP_ID     NUMBER,
      COUNTRY_NO VARCHAR2(15)
    alter table EMP_DOCS
      add constraint PK_EMP_DT primary key (ID);
    alter table EMP_DOCS
      add constraint FK_EMP_DT foreign key (EMP_ID)
      references EMP (ID);
    create table EMP_ITEMS
      ID         NUMBER not null,
      EMP_DOC_ID     NUMBER
    alter table EMP_ITEMS
      add constraint PK_EMP_ITEMS_DT primary key (ID);
    alter table EMP_ITEMS
      add constraint FK_EMP_ITEMS_DT foreign key (EMP_DOC_ID)
      references EMP_DOCS (ID);
      create table DOCUMENT
      ID   NUMBER not null,
      DOCNO VARCHAR2(15),
      INVOICE_REF_1 NUMBER
    alter table DOCUMENT
      add constraint DOC_PK_ID primary key (ID);
      create table DOCUMENT_ITEMS
      ID         NUMBER not null,
      DOC_ID     NUMBER,
      EMP_ITEMS_REF_ID_1    NUMBER
    alter table DOCUMENT_ITEMS
      add constraint PK_DOCUMENT_ITEMS_DT primary key (ID);
    alter table DOCUMENT_ITEMS
      add constraint FK_DOCUMENT_ITEMS_DT foreign key (DOC_ID)
      references DOCUMENT (ID);
    create table INVOICE
      ID   NUMBER not null,
      INVOICE_NO VARCHAR2(15)
    alter table INVOICE
      add constraint INVOICE_PK_ID primary key (ID);
      INSERT INTO EMP ( ID, TYPE ) VALUES (
    1, 'A');
    INSERT INTO EMP ( ID, TYPE ) VALUES (
    2, 'A');
    INSERT INTO EMP ( ID, TYPE ) VALUES (
    3, 'A');
    INSERT INTO EMP ( ID, TYPE ) VALUES (
    4, 'A');
    INSERT INTO EMP_DOCS ( ID, EMP_ID, COUNTRY_NO ) VALUES (
    1, 1, 'INDIA');
    INSERT INTO EMP_DOCS ( ID, EMP_ID, COUNTRY_NO ) VALUES (
    2, 2, 'INDIA');
    INSERT INTO EMP_DOCS ( ID, EMP_ID, COUNTRY_NO ) VALUES (
    3, 3, 'INDIA');
    INSERT INTO EMP_DOCS ( ID, EMP_ID, COUNTRY_NO ) VALUES (
    4, 4, 'USA');
    INSERT INTO EMP_ITEMS ( ID, EMP_DOC_ID ) VALUES (
    1, 1);
    INSERT INTO EMP_ITEMS ( ID, EMP_DOC_ID ) VALUES (
    2, 2);
    INSERT INTO EMP_ITEMS ( ID, EMP_DOC_ID ) VALUES (
    3, 3);
    INSERT INTO EMP_ITEMS ( ID, EMP_DOC_ID ) VALUES (
    4, 4);
    INSERT INTO DOCUMENT ( ID, DOCNO, INVOICE_REF_1 ) VALUES (
    1, 'DOC1', 1);
    INSERT INTO DOCUMENT ( ID, DOCNO, INVOICE_REF_1 ) VALUES (
    2, 'DOC1', 2);
    INSERT INTO DOCUMENT ( ID, DOCNO, INVOICE_REF_1 ) VALUES (
    3, 'DOC3', 0);
    INSERT INTO DOCUMENT ( ID, DOCNO, INVOICE_REF_1 ) VALUES (
    4, 'DOC4', 3);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    1, 1, 1);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    2, 2, 2);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    3, 2, 2);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    4, 3, 3);
    INSERT INTO DOCUMENT_ITEMS ( ID, DOC_ID, EMP_ITEMS_REF_ID_1 ) VALUES (
    5, 4, 4);
    INSERT INTO INVOICE ( ID, INVOICE_NO ) VALUES (
    1, 'INV1');
    INSERT INTO INVOICE ( ID, INVOICE_NO ) VALUES (
    2, 'INV2');
    INSERT INTO INVOICE ( ID, INVOICE_NO ) VALUES (
    3, 'INV3');
    commit;
    -- I have written below query to satisfy above conditions but still required results are not coming..
    SELECT *
      FROM EMP E
    WHERE E.TYPE = 'A'
       AND NOT EXISTS (SELECT *
              FROM EMP_DOCS       EDOC1,
                   EMP_DOCS       EDOC2,
                   EMP            E1,
                   EMP_ITEMS      EMPI,
                   DOCUMENT_ITEMS DOCITM,
                   DOCUMENT       DOC,
                   INVOICE        INV
             WHERE EDOC1.EMP_ID = E.ID
               AND EDOC2.EMP_ID = E1.ID
               AND EDOC1.ID = EMPI.EMP_DOC_ID
               AND EDOC1.COUNTRY_NO = EDOC2.COUNTRY_NO
               AND EMPI.ID = DOCITM.EMP_ITEMS_REF_ID_1
               AND DOCITM.DOC_ID = DOC.ID
               AND INV.ID = DOC.INVOICE_REF_1);

    DB version:oracle 10g;10.2

  • How to rewrite the query

    hi ,
    Actual i write the query like this , and run this query in sql developer ,
    it will take more than 15 mins
    alloc_details table -- 2 lac records
    doc_details -- 2 lac records
    query :
    SELECT
         a.activity
    ,      sum( a.lamt ) lamt
    ,      sum( a.lamt ) camt
    FROM
         alloc_detail a
    WHERE
         a.alc_code <>'JOB'
    And      a.alc_value is not null
    And      EXISTS ( SELECT
                   distinct b.doc_no
         FROM
                   doc_detail b
         WHERE
                   a.org=b.org
         And      a.doc_no=b.doc_no
         And      a.doc_type=b.doc_type
         And      ( b.dr_act_code='11111' OR b.cr_act_code='111111')
         And      ( ( trunc( b.doc_date ) >='01-jan-08' ) )
         And      ( ( trunc( b.doc_date ) <= '31-jan-08' ) )
    GROUP BY
         a.alc_value
    Anyother way to rewrite the query .

    Is this query working? a.activity seems to be a "not a group by expression"
    select a.activity,sum(a.lamt) lamt,sum(a.lamt) camt  /* 2 times same sum - a typo ? */
      from alloc_detail a
    where a.alc_code != 'JOB'      /* not equal presumed */
       and a.alc_value is not null
       and exists(select distinct b.doc_no
                    from doc_detail b
                   where a.org = b.org
                     and a.doc_no = b.doc_no
                     and a.doc_type = b.doc_type
                     and (b.dr_act_code = '11111' or b.cr_act_code = '111111')
                     and trunc(b.doc_date) >= '01-jan-08'
                     and trunc(b.doc_date) <= '31-jan-08'
    group by a.alc_valuehow about applying predicates first
    select a.alc_value,sum(a.lamt) lamt,sum(a.camt) camt
      from (select alc_value,lamt,camt,org,doc_no,doc_type
              from alloc_detail
             where alc_code != 'JOB'
               and alc_value is not null
           ) a,
           (select distinct org,doc_no,doc_type
              from doc_detail
             where doc_date >= to_date('01-jan-08','dd-mon-rr')
               and doc_date <= to_date('31-jan-08','dd-mon-rr') + 1 - 1/24/60/60
               and (dr_act_code = '11111' or cr_act_code = '111111')
           ) b
    where a.org = b.org
       and a.doc_no = b.doc_no
       and a.doc_type = b.doc_type
    group by a.alc_valueRegards
    Etbin

  • How to generate mdx query using C#

    I am new to mdx query and i am very curious about mdx query generation using c# so i searched for any demo or open source then i found
    Ranet.olap, which is providing what i need. After taking the dlls i tried to incorporate them in my code. I am pasting my full
    console code which should generate mdx query but it's not doing so, Am i doing something wrong.
    using System;
    using System.Collections.Generic;
    using Microsoft.AnalysisServices.AdomdClient;
    using Ranet.Olap.Core.Managers;
    using Ranet.Olap.Core.Metadata;
    using Ranet.Olap.Core.Types;
    namespace MDX
        class Program
            static void Main(string[] args)
                startWork();
            public static void startWork()
                string connString = "Provider=MSOLAP.3; Data Source=localhost;Initial Catalog=AdventureWorkDW2008R2;Integrated Security=SSPI;";
                CubeDef cubes;
                AdomdConnection conn = new AdomdConnection(connString);
                conn.Open();
                cubes = conn.Cubes.Find("AdventureWorkCube");
                Ranet.Olap.Core.Managers.MdxQueryBuilder mdx = new Ranet.Olap.Core.Managers.MdxQueryBuilder();
                mdx.Cube = cubes.Caption;
                List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listColumn = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
                List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listRow = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
                List<Ranet.Olap.Core.Wrappers.AreaItemWrapper> listData = new List<Ranet.Olap.Core.Wrappers.AreaItemWrapper>();
                //Column area
                Dimension dmColumn = cubes.Dimensions.Find("Dim Product");
                Microsoft.AnalysisServices.AdomdClient.Hierarchy hColumn = dmColumn.Hierarchies["English Product Name"];
                //hierarchy properties
                List<PropertyInfo> lPropInfo = new List<PropertyInfo>();
                foreach (var prop in hColumn.Properties)
                    PropertyInfo p = new PropertyInfo();
                    p.Name = prop.Name;
                    p.Value = prop.Value;
                    lPropInfo.Add(p);
                Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIColumn = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
                areaIColumn.AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper;
                areaIColumn.Caption = hColumn.Caption;
                areaIColumn.CustomProperties = lPropInfo;
                listColumn.Add(areaIColumn);
                //Rows Area
                Dimension dmRow = cubes.Dimensions.Find("Due Date");
                Microsoft.AnalysisServices.AdomdClient.Hierarchy hRow = dmRow.Hierarchies["English Month Name"];
                List<PropertyInfo> lRowPropInfo = new List<PropertyInfo>();
                foreach (var prop in hRow.Properties)
                    PropertyInfo p = new PropertyInfo(prop.Name,prop.Value);
                    lRowPropInfo.Add(p);
                Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIRow = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
                areaIRow.AreaItemType = AreaItemWrapperType.Hierarchy_AreaItemWrapper;
                areaIRow.Caption = hRow.Caption;
                areaIRow.CustomProperties = lRowPropInfo;
                listRow.Add(areaIRow);
                //Measure Area or Data Area
                Measure ms = cubes.Measures.Find("Order Quantity");
                Ranet.Olap.Core.Wrappers.AreaItemWrapper areaIData = new Ranet.Olap.Core.Wrappers.AreaItemWrapper();
                areaIData.AreaItemType = AreaItemWrapperType.Measure_AreaItemWrapper;
                areaIData.Caption = ms.Caption;
                List<PropertyInfo> lmpropInfo = new List<PropertyInfo>();
                foreach (var prop in ms.Properties)
                    PropertyInfo p = new PropertyInfo(prop.Name, prop.Value);
                    lmpropInfo.Add(p);
                areaIData.CustomProperties = lmpropInfo;
                listData.Add(areaIData);
                mdx.AreaWrappersColumns = listColumn;
                mdx.AreaWrappersRows = listRow;
                mdx.AreaWrappersData = listData;
                string mdxQuery = mdx.GenerateMdxQuery();
                conn.Close();

    Hi mkm1,
    According to your description, you want to use C# code to generate MDX Query. Right?
    In Analysis Servcies, we just need to use "Microsoft.AnalysisServices.AdomdClient.dll" to open connection to SSAS database and retrieve data from cube. Here are some sample code about executing MDX query using C#.
    Dim objConnection As New AdomdConnection("Data Source=localhost;Initial Catalog=Adventure Works DW 2008;")
    Dim objCommand As New AdomdCommand()
    Dim objDatatable As New DataTable
    Dim strCommand As String
    strCommand = "SELECT [Measures].[Internet Sales Amount] ON COLUMNS, "
    strCommand = strCommand & " [Date].[Calendar].[Calendar Year] ON ROWS"
    strCommand = strCommand & " FROM [Adventure Works]"
    objConnection.Open()
    objCommand.Connection = objConnection
    objCommand.CommandText = strCommand
    Dim objDataAdapter As New AdomdDataAdapter(objCommand)
    objDataAdapter.Fill(objDatatable)
    objConnection.Close()
    Since your code is more related to a third party API, we suggest you post your question to Rnet.
    Reference:
    Microsoft.AnalysisServices.AdomdClient Namespace
    If you have any question, please feel free to ask.
    Simon Hou
    TechNet Community Support

  • How to create a query using the requirements given ? step by step  plz

    REQUIREMENTS
    1)     Model- Use multiprovider ZXT_MXXX as infoproviders
    2)     Query- copy ‘ZXT_MXXX_QYYY’ as head start
    <b>b.     Fields for output</b>
    1.     Hourly Rate-- I know its dataflow .It comes from infotype IT yyyy
    Program name MPyyyy00 and query name QXXXX-XXXX
    So can I Get this feild to Query Designer
    2.     CC /WBS/IO on ITyyyy--?
    I know dataflow .they come from infotype IT yyyy
    Program name MPyyyy00 and  3 different fields.
    So how can I Get cc/wbs to Query Designer?
    Can anyone suggests steps to do it plz..

    Check the<b> ZXT_MXXX</b>  multiproivder is based on what all infoproviders..
    Check in your infoproviders..for this <b>CC /WBS/IO</b>field..
    If it is avialable in the underlying infoproviders, it should be available for your reporting on multiprovider..
    Regards
    Manga

  • How to feed a query using a variable defined as Replacement Path-Query

    Scenario description : BI NetW 2004S - InfoCube with the following characteristics Customer, OrderDate, OrderYear and the following KeyFigure Number of Pieces.
    Objective: I need a query "QB" that shows how many pieces a set of customers has ordered in the year 2008. The set of customers is defined as all customers that in the previous years (the user can select one or more years) have ordered more than 500 pieces within the same year.
    Implementation: In general terms the idea is to build a query "QB" with the characteristic "Customer"  that is restricted (filtered) using a variable that is fed by another query "QA" (Replacement Path-Query).
    In order to have the selection of customers that for each of previous years (2007, 2006, 2005,...) have ordered more than 500 pieces, in the query "QA":
    - I put OrderYear as filter and defined a variable in order to ask the user which year/s he wants to analyse to define the selection
    - I put Customer and OrderYear in row
    - I put the KeyFigure Number of Pieces in column
    - I've defined the following condition: Number of Pieces > 500 with the option Caracteristic Assignment = All Characteristics in the Drilldown Indipendently
    Now if I run the query "QA" it works correctly showing me all customers that in the selected years have ordered more than 500 pieces within of the same year.
    If I run the query "QB" it shows a correct result only if I enter only one year (for example 2006) in the OrderYear field (coming from the query "QA"); if I enter more than one year (for example 2006 and 2007) the selection of customers showed is not the same defined by the first query "QB": I was expecting to see all customers defined from the first query less all customers that have no ordered any piece in 2008.
    Questions
    1) Why is query "QA" working on a different selection of customers when the user selects more than one year?
    2) Cosidering the scenario and the objective described above do you have any other idea?
    Thanks
    Ciao
    Roberto

    Hi Christophe,
         it's ok for me if I consider the customer only once in the final selection of customers that feeds the final query, this is my objective.
    However as test I've created 2 "input" queries, one related to 2006 and one related to 2007, and then in my destination query I've tried to restrict the customer using 2 variables of type replacement path-query (one attached to the 2006 query and one attached to the 2007 query). Unfortunately when I try to check and save the destination query, Query Designer tells me it is not possible to restrict the characteristic in this way.
    Could you please describe me steps you run in to order to restrict a characteristic using more than one variable of type replacement path-query?
    Thank you in advance for your answer.
    Ciao,
    Roberto

  • How to rewrite this query to avoid duplicates , please

    Hello Good Morning All,
    Happy New Year,
    Could you please help to rewrite the below two queries (so that i can avoid duplicates) i need to send email to everyone not the dupllicated ones), please?
    Create table #MyPhoneList
     AccountID int,
     EmailWork varchar(50),
     EmailHome varchar(50),
     EmailOther varchar(50),
     IsOffersToWorkEmail bit,
     IsOffersToHomeEmail bit,
     IsOffersToOtherEmail bit,
     IsValidEmailWork bit,
     IsValidEmailHome bit,
     IsValidEmailOther bit
    --> In this table AccountID is uniquee
    --> email values could be null or repetetive for work / home / Other (same email can be used more than one columns for accountid)
    -- a new column will be created with name as Sourceflag( the value could be work, Home, Other depend on email coming from) then removes duplicates
    SELECT AccountID , Email, SourceFlag, ROW_NUMBER() OVER(PARTITION BY AccountID, Email ORDER BY Sourceflag desc) AS ROW
    INTO #List
    from (
      SELECT AccountID
         , EmailWork      AS EMAIL
         , 'Work'       AS SourceFlag
      FROM #MyPhoneList (NoLock) eml
      WHERE IsOffersToWorkEmail    = 1
      AND  EMAILWORK      IS NOT NULL
      AND  IsValidEmailWork    = 1
     UNION
      SELECT AccountID
         , EmailHome  
         , 'Home'       AS SourceFlag
      FROM #MyPhoneList (NoLock) eml
      WHERE IsOffersToHomeEmail    = 1
      AND  EMAILHOME      IS NOT NULL
      AND  IsValidEmailHome    = 1
     UNION
      SELECT AccountID
         , EmailOther  
         , 'Other'       AS Sourceflag
      FROM #MyPhoneList (NoLock) eml
      WHERE EmailOther      = 1
      AND  EMAILOther      IS NOT NULL
      AND  IsValidEmailOther    = 1
     ) eml --select count(*) from #email
    --Email dedupe on source
    SELECT * INTO #distinct FROM #List WHERE ROW  = 1
    Thank you in Advance
    Milan

    Please follow basic Netiquette and post the DDL we need to answer this. Follow industry and ANSI/ISO standards in your data. You should follow ISO-11179 rules for naming data elements. You should follow ISO-8601 rules for displaying temporal data. We need
    to know the data types, keys and constraints on the table. Avoid dialect in favor of ANSI/ISO Standard SQL. And you need to read and download the PDF for: 
    https://www.simple-talk.com/books/sql-books/119-sql-code-smells/
    >> Could you please help to rewrite the below two queries (so that I can avoid duplicates) I need to send email to everyone not the duplicated ones), please? <<
    This mess is not a table because it has no keys, not way to have a key. You are using UNION like we used punch card merges in the o9ld days. 
    What math do you do on the account_id? That is the only reason that you use numeric values Why do you think that an email is fifty characters long? Yes, most them are, but did you bother to look at the maximum length? NO! Why did you name it “Phone_List” when
    it is nothing but email addresses? emails are not phones.  
    Please read this article so you will know why RDBMS does not use assembly language flags like you are doing. 
    https://www.simple-talk.com/sql/t-sql-programming/bit-of-a-problem/
    It would also help if you know what normalization was. Here is one design that is valid. 
    CREATE TABLE Something_emails 
    (account_id CHAR(15) NOT NULL,
     email_address VARCHAR(256) NOT NULL,
     email_type CHAR(5) NOT NULL
     CHECK (email_type IN ('home', 'work', 'misc')),
     PRIMARY KEY (email_address, email_type)
    >> In this table account_id is unique <<
    No, not without the DDL you did not post.
    >> email values could be NULL or repetitive for work / home / Other (same email can be used more than one columns for account_id) <<
    Not a problem. Look at the primary key.  Also why would anyone store invalid data in a table? SQL programmers try to keep it out! 
    >> a new column will be created with name as Source_flag (the value could be work, Home, Other depend on email coming from) then removes duplicates <<
    More kludges! Oh, putting the comma at the front of a line is how non-SQL mimic punch cards. An SQL progtrqammer would put related subsets of columns on one line – we think in sets! After 30+ years of SQL, this is one of the code smells I use to find bad
    code. 
    --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 to Find the Query used by the Workbook ?

    Hi ,
    I am currently involved in trouble shooting a work book where some master data values are not being displayed.
    How do i find, which Query the work books is using ? or Let me know as to how should i proceed in solving the same .

    Hi,
    If you have access to BW Admin workbench... then choose the option metadatarepository(left side) of the BW admin workbench, search for the workbook(Technical name) and click on the "Network display dataflow" link.
    If you want to know the relationship between workbook and the queries:
    Check table RSRWORKBOOK which contains the WORKBOOKID and the GENUNIID.
    Table RSRREPDIR contains GENUNIID, query name RNAME, AUTHOR, LASTUSER, INFOCUBE
    Table RSRINDEXT contains the WORKBOOKID and workbook TITLE
    You should join the tables by GENUNIID and select in RSRREPDIR the rows that have COMPTYPE='REP' for queries and object version active/modified.
    With this information an infoset query can be created to list all workbook-query-user relationship (and even the query-infocube relationship).
    Hope this helps u...
    Regards,
    KK.

  • How to write a query use between two months

    Hello,
    I have two views v1 and v2. Both have two columns c1 and c2: c1 with mon-yyyy format, c2 is a number. I am writing a query like this;
    select v1.c2, v2.c2 from v1, v2
    where v1.c1 = v2.c1 and v1.c1 between to_date('Jan-2011','mon-yyyy')
    and to_date('Dec-2011','mon-yyyy')
    i got: ORA-01858: a non-numeric character was found where a numeric was expected
    V1 and V2 value are like these:
    Mon-2011 89
    Feb-2011 33
    Mar-2011 45
    Apr-2011 98
    How to make it work.
    Thanks for your help.
    Jen

    Hello Jen Hu,
    Try this:
    with t as ( select 'feb-2011' as c1, 33 as nr from dual union
    select 'mar-2011',45 from dual union
    select 'apr-2011',98 from dual union
    select 'jun-2011',86 from dual union
    select 'jul-2011',78 from dual union
    select 'aug-2011',87 from dual union
    select 'sep-2011',68 from dual union
    select 'oct-2011',56 from dual union
    select 'nov-2011',68 from dual union
    select 'dec-2011',55 from dual union
    select 'jan-2012',54 from dual
    ) SELECT * FROM T
    where to_date(c1,'mon-yyyy') between to_date('aug-2011','mon-yyyy') and to_date('dec-2011','mon-yyyy');@Tauceef:
    >
    Tauceef wrote:
    You have to store full date, the conversion you are doing to_date('jan-2011','mon-yyyy') is not at all accepted, this is where you are getting that error.
    >
    Why not? Have you tried:
    select to_date('jan-2011','mon-yyyy') from dual;Once you convert the character string into date it is easier to compare!
    I agree with @clcarter's point:
    >
    Firstly, if you want to compare dates, use a DATE datatype, not varchar2. If the varchar2 has invalid dates you'll have all sorts of trouble. 'Feb-31-2011' is a perfectly valid string. But its not a date.
    >
    But if you have better mechanism of valid string input as in here:
    http://apex-plugin.com/oracle-apex-plugins/item-plugin/month-picker_148.html
    then problems of invalid string input are minimized!
    Hope it helps!
    Regards,
    Kiran

Maybe you are looking for

  • ADDING NEW FIELDS IN me21n

    Hi Gurus,            m added 5 custom fields in PO header customer data. for tht, include of EKKO added 5 fields. m using enhancement MM06E005 for screen layout and updation,' 1) EXIT_SAPMM06E_007   (PAI) - Export data 2) EXIT_SAPMM06E_006   (PBO) 3)

  • How to diable JDialog on refresh of a data in a tab

    Hi, I have an application which has a tab1 which contains a Jtable.On clicking a cell in Jtable a JDialog appears showing some more info on the cell clicked. Now i want to do this... When i refresh the tab1 the corresponding Jdialog should become emp

  • Error in simple javascript search web-part.

    Hi everybody. I need a help. I want to write simple sharepoint farm solution web-part (not App) with javascript for search like describe http://www.dotnetmafia.com/blogs/dotnettipoftheday/archive/2013/04/18/how-to-query-search-with-the-sharepoint-201

  • Cursor Expression

    Is Cursor Expression in Select list  allowed in SQL Server?  

  • Is Acrobat Reader supported by Adobe on App-V?

    We are planning a desktop upgrade to Windows 8.1 with apps running on App-V, Is Acrobat Reader supported by Adobe on App-V?