Left joins : Case or if statement

Hi
I want to know if one can build in a case or if statement into a left join. I want to multiply a value with -1 if the condition is met.

I think it is not possible in SELECT statement...but you can do the below to resolve it.
add a field for FKART in your internal table.
TYPES: BEGIN OF tab ,
       kunag LIKE vbrk-kunag,
       fkdat like vbrk-fkdat,
       matnr LIKE vbrp-matnr,
       werks LIKE vbrp-werks,
       fkart like vbrk-fkart,
       volum LIKE vbrp-volum,
       END OF tab.
DATA: wa_outtab TYPE table of tab WITH HEADER LINE.
SELECT akunag  afkdat
       bmatnr bwerks a~fkart
       SUM( b~volum )
   INTO  table wa_outtab
FROM vbrk AS a
INNER JOIN vbrp AS b
      ON  avbeln  = bvbeln
WHERE
avbeln = bvbeln                                                                               
AND ( afkart LIKE 'F2' OR afkart LIKE 'RE' )
GROUP BY  akunag afkdat bmatnr bwerks a~fkart.
sort wa_outtab.
Loop at wa_outtab.
  if wa_outtab-fkart = 'RE'.
    lpos = lpos +  wa_outtab-volum.
  else.
    lneg = lneg +  wa_outtab-volum.
  endif.
  at end of werks.
     lvaule = lpos - lneg.
    lpos = lneg = 0.
  endat.
endloop.

Similar Messages

  • SQL statement that includes LEFT & RIGHT JOIN in the same statement??? Help

    Hi,
    How an I write an SQL statement with a GROUP BY that will both (a) include the NULL value from the left hand table, but also (b) include ALL columns from the right hand table. It's like I need a LEFT JOIN and a RIGHT JOIN in the query at the same time.
    Here's an example of the 2 tables I have and the result I'm after. As you can see I want the NULL's from Expenses Table summed, as well as include all categories from the right hand table (i.e. even if there are no expenses against them)
    Table = Expenses
    Amount Category
    $10 1
    $20 2
    $30 1
    $40 NULL {i.e. not yet categorised}
    Table = Categories
    ID Title
    1 Food
    2 Entertainment
    3 Travel
    4 Personal
    REQUIRED RESULT
    Category Total
    Food 40
    Entertainment 20
    Travel 0
    Personal 0
    NULL 40
    Thanks

    SQL> create table expenses (amount,category)
      2  as
      3  select 10, 1 from dual union all
      4  select 20, 2 from dual union all
      5  select 30, 1 from dual union all
      6  select 40, null from dual
      7  /
    Table created.
    SQL> create table categories (id,title)
      2  as
      3  select 1, 'Food' from dual union all
      4  select 2, 'Entertainment' from dual union all
      5  select 3, 'Travel' from dual union all
      6  select 4, 'Personal' from dual
      7  /
    Table created.
    SQL> select c.title category
      2       , nvl(sum(e.amount),0) total
      3    from expenses e
      4         full outer join categories c on (e.category = c.id)
      5   group by c.id
      6       , c.title
      7   order by c.id
      8  /
    CATEGORY                                       TOTAL
    Food                                              40
    Entertainment                                     20
    Travel                                             0
    Personal                                           0
                                                      40
    5 rows selected.Regards,
    Rob.

  • LEFT JOIN error

    Hi,
    While running this query I get following error In Orcale Forms Developer 10.2.0.2 and DB 10g but when I run same query in SQL Plus it
    throws no errors.
    Encountered the symbol "LEFT" when expecting one of the following
    for group having intersect minus order stat union where connect.
    PROCEDURE post_query IS
      BEGIN
            SELECT  /*+ USE_HASH(o,stm) */
                      NVL(SUM(CASE o.status WHEN 'P' THEN 1 ELSE 0 END),0),
                      NVL(SUM(CASE o.status WHEN 'E' THEN 1 ELSE 0 END),0),
                      NVL(SUM(CASE o.status WHEN 'B' THEN 1 ELSE 0 END),0),
                      NVL(SUM(CASE WHEN o.status IN ('A','U') AND (NVL(o.priority,'1') = '2' OR stm.surcharge_amount !=  0) THEN 1 ELSE 0 END),0),
                      NVL(SUM(CASE WHEN o.status IN ('A','U') AND (NVL(o.priority,'1') != '2' OR stm.surcharge_amount =  0) THEN 1 ELSE 0 END),0)
                INTO  :ORDER_STATUS.PENDING,
                      :ORDER_STATUS.ERROR,
                      :ORDER_STATUS.BACK_ORDER,
                      :ORDER_STATUS.EXPEDITE,
                      :ORDER_STATUS.STD_SHIP
                 FROM orders o
                 LEFT JOIN shipment_type_methods stm
                   ON (o.client = stm.client AND o.shipment_class_code = stm.shipment_class_code)
                WHERE o.status IN ('B', 'E', 'P', 'A', 'U')
                  AND (parent_order_id is null
                   OR (order_type='G'
                  AND parent_order_id=original_order_number))
                  AND o.client = :ORDER_STATUS.CLIENT_NUMBER;
      END post_query;Please help me to fix it.
    Thanks
    Sandy

    Hi Mathew,
    The ugly table aliases aside: What happens when you try to run this query?
    Give more info like sample data, desired output, exact error messages...
    Rgds,
    Guido

  • Left join and where clause with not equal ( ) returns too many rows

    Say I have something like this
    Table A
    =========
    Id
    OrderNum
    Date
    StoreName
    AddressKey
    Table B
    ========
    Id
    StreetNumber
    City
    State
    select a.* from [Table A] a
    left join [Table B] b on a.AddressKey = b.Id
    where a.StoreName <> 'Burger place'
    The trouble is that the above query still returns rows that have StoreName = 'Burger place'
    One way Ive handled this is to use a table expression, select everything into that, then select from the CTE and apply the filter there.  How could you handle it in the same query however?

    Hi Joe,
    Thanks for your notes.
    INT SURROGATE PRIMARY KEY provides a small footprint JOIN ON column. Hence performance gain and simple JOIN programming.  In the Addresses table, address_id is 4 bytes as opposed to 15 bytes san. Similarly for the Orders table.
    INT SURROGATE PRIMARY KEY is a meaningless number which can be duplicated at will in other tables as FOREIGN KEY.  Having a meaningful PRIMARY KEY violates the RDBMS basics about avoiding data duplication.  If I make CelebrityName (Frank Sinatra)
    a PRIMARY KEY, I have to duplicate "Frank Sinatra" as an FK wherever it needed as opposed to duplicating SURROGATE PRIMARY KEY CelebrityID (79) a meaningless number.
    This is how we design in SQL Server world.
    QUOTE from Wiki: "
    Advantages[edit]
    Immutability[edit]
    Surrogate keys do not change while the row exists. This has the following advantages:
    Applications cannot lose their reference to a row in the database (since the identifier never changes).
    The primary or natural key data can always be modified, even with databases that do not support cascading updates across related
    foreign keys.
    Requirement changes[edit]
    Attributes that uniquely identify an entity might change, which might invalidate the suitability of natural keys. Consider the following example:
    An employee's network user name is chosen as a natural key. Upon merging with another company, new employees must be inserted. Some of the new network user names create conflicts because their user names were generated independently (when the companies
    were separate).
    In these cases, generally a new attribute must be added to the natural key (for example, an
    original_company column). With a surrogate key, only the table that defines the surrogate key must be changed. With natural keys, all tables (and possibly other, related software) that use the natural key will have to change.
    Some problem domains do not clearly identify a suitable natural key. Surrogate key avoids choosing a natural key that might be incorrect.
    Performance[edit]
    Surrogate keys tend to be a compact data type, such as a four-byte integer. This allows the database to query the single key column faster than it could multiple columns. Furthermore a non-redundant distribution of keys causes the resulting
    b-tree index to be completely balanced. Surrogate keys are also less expensive to join (fewer columns to compare) than
    compound keys.
    Compatibility[edit]
    While using several database application development systems, drivers, and
    object-relational mapping systems, such as
    Ruby on Rails or
    Hibernate, it is much easier to use an integer or GUID surrogate keys for every table instead of natural keys in order to support database-system-agnostic operations and object-to-row mapping.
    Uniformity[edit]
    When every table has a uniform surrogate key, some tasks can be easily automated by writing the code in a table-independent way.
    Validation[edit]
    It is possible to design key-values that follow a well-known pattern or structure which can be automatically verified. For instance, the keys that are intended to be used in some column of some table might be designed to "look differently from"
    those that are intended to be used in another column or table, thereby simplifying the detection of application errors in which the keys have been misplaced. However, this characteristic of the surrogate keys should never be used to drive any of the logic
    of the applications themselves, as this would violate the principles of
    Database normalization"
    LINK: http://en.wikipedia.org/wiki/Surrogate_key
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Database Design
    New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

  • Query problem, two working queries how to left join together?

    Hello,
    I have a two queries that I have been trying to put together for a couple days. I'm frazzled. Hopefully you can help.
    The first query returns all rows from the database. The second query returns only one row (because the way it is currentlly set up in the Where clause). So I know that will have to change. For each row returned in Query1, I need the two fields from Query2 included
    (so the link would be through client.Id (which is an indexed field) or client.Accountnumber?
    This query, returns all records in the database:
    Select client.Id, client.accountnumber, client.Namelast,
    dmlocation.city ||', '||dmlocation.state as CityState,
    client.salesTerritory_client ||'-'|| dmuser.namefirst_user ||' '|| dmuser.namelast_user as Territory,
    MaxDates.LastRun, client.creditrisk, client.customercategory
    from client
    Left join fctclientcoverage on fctclientcoverage.client_id = client.id
    Left join dmlocation on fctclientcoverage.location_id = dmlocation.id
    Left join dmuser on dmuser.id = client.id
    Left join (Select to_char(Max(dmdate.calendardate),'MM/DD/YY') as LastRun, Client.Id
    from dmdate, client, fctadorder
    where dmdate.id = fctadorder.lastinsert_date_id and client.id = fctadorder.primaryorderer_client_id
    group by client.id) MaxDates ON client.id = MaxDates.Id
    where(fctclientcoverage.Ccoverrecordstopdate Is Null)
    Order by client.namelast;
    Query 2, only returns 1 row, so for each row returned above, the two fields selected in this query should accompany each row. But how to link these two selects using the client.accountnumber (or perhaps by dmcliet.id)?
    Select booked.CurRev, booked.LastRev from (
    Select (sum(Case When dmDate.CalendarDate &gt;= '29-DEC-2008' and dmDate.CalendarDate &lt; '
    Then fctinsertchargedetail.Amount_insertDetail Else 0 End)) As CurRev,
    (sum(Case When dmDate.CalendarDate &gt;= '29-DEC-2007' and dmDate.CalendarDate &lt; '
    Then fctinsertchargedetail.Amount_insertDetail Else 0 End)) As LastRev
    from fctAdorder
    Inner Join client On fctAdorder.primaryorderer_client_id = client.id
    Inner Join fctinsertion On fctAdorder.id=fctinsertion.fctAdorder_id
    Inner Join fctinsertchargesummary On fctinsertion.id=fctinsertchargesummary.insertion_id
    Inner Join dmDate On fctinsertion.insert_date_id=dmDate.id
    Inner Join fctinsertchargedetail On fctinsertchargesummary.id=fctinsertchargedetail.insertchargesummary_id
    WHERE client.accountnumber = '12345678' and
    dmDate.CalendarDate &gt;= '29-DEC-2007' And dmDate.CalendarDate &lt; ') booked;
    Thanks for your time.

    Yes, You are correct!
    I just recently got the query working with the aid of another forum.
    The sad part is, all though the first query took 11 seconds to return 180,000 rows (thats good); The second query took 4 minutes to calculate and return all it's rows (that's bad). Together the query ran for over 4 minutes. Way too slow.
    Being brand new to oracle I have to try and figure away to cut this time down. Perhaps I'm not considering something?
    I orginally brought into my .net app the results from the first query and then in the rowdatabound event I queried each row to get the information needed from the second query. That was way too slow also. It was recommended to try and return all needed data at once.
    I've been given a task to emulate a current application, (which I do not have access to it's code), that brings back all of this same information that I am using. It only takes them maybe 15 seconds to run, to bring back all. Of course they were experienced oracle sql developers.
    So I guess my next step is to try and improve that second query. Thanks for replying to this Frank. I'll be back. Are you or is anyone good at knowing how to optimzie queries? I'm reading a book now trying out suggestions. Nothing is working yet.
    thanks

  • Left join (+) instead of "not in"

    Hi all!
    I've got statement with "where dig not in (840, 978)" string.
    How do I write statement without "not in" ?
    I thought about left join and "is not null", but don't know exactly how to use it.
    Any ideas?
    Thanks ahead.

    Here is my solution:
    select d.* from
    (select 111 as accountno, 840 as currencyid from dual
    union all
    select 222 as accountno, 978 as currencyid from dual
    union all
    select 333 as accountno, 826 as currencyid from dual ) d ,
    (select 840 as dig from dual
    union all
    select 978 as dig from dual ) j
    where d.currencyid = j.dig(+)
    and j.dig is null
    Thanks to all.

  • LEFT Join not working

    Hi guys,
    I am not sure why the left join is not working.. when I try to use the and condition out of the left join condition. The database is relational but the requirement is for reporting. I have 2 user inputs and I should get the query results as explained below..
    Let me explain with the sample data.
    Table 1: PRTYPE (P)
    TYPEID CLASSID
    T001 CLS001
    T001 CLS002
    T001 CLS003
    T002 CLS002
    T003 CLS001
    Table 2: EMPLOYEE (E)
    EMPID NAME
    E001 Joe
    E002 Mark
    E003 Lucy
    Table 3: DETAILS (D)
    EMPID CLASSID STATUS
    E001 CLS001 NEW
    E001 CLS002 DONE
    E002 CLS001 NEW
    E002 CLS004 NEW
    Report1:
    Input: PRTYPE.TYPEID = T001, EMPID = E001
    Output:
    E.NAME E.EMPID P.TYPEID A.CLASSID D.STATUS
    JOE EMP001 T001 CLS001 NEW
    JOE EMP001 T001 CLS002 DONE
    JOE EMP001 T001 CLS003 BLANK
    Report2:
    PRTYPE.TYPEID = T003, EMPID = E003
    E.NAME E.EMPID P.TYPEID A.CLASSID D.STATUS
    LUCY E003 T003 CLS001 BLANK
    LUCY E003 T003 CLS004 BLANK
    When I use and condition in left join itself, it works but when I take it to the end of the sql using where p.typeid= T001 and E.EMPID = E001 I am not getting the left join results... It looks like Oracle doesn't like the condition at the end. I hope I am clear on explaining. Please share your experience on how to get it working..
    Thank you

    Hi,
    Welcome to the forum!
    user12118328 wrote:
    I am not sure why the left join is not working.. when I try to use the and condition out of the left join condition. The database is relational but the requirement is for reporting. I have 2 user inputs and I should get the query results as explained below..
    When I use and condition in left join itself, it works but when I take it to the end of the sql using where p.typeid= T001 and E.EMPID = E001 I am not getting the left join results... It looks like Oracle doesn't like the condition at the end. I hope I am clear on explaining. Please share your experience on how to get it working..I'm not sure what you mean. Why don't you post your query? You know, it will be easier for someone to tell you what you're doing wrong if they know what you're doing.
    Are you saying that you get the correct results when you have a cerain condition in an outer join, but that you get the wrong results if you put the exact same condition in the WHERE-clause?
    If so, keep the condition where it does what you want.
    You can usually move INNER join conditions around like that, but never OUTER join conditions.
    As Alex said, if you want help, post executable statement to create and populate your tables with a little sample data, as well as the output you want from that sample data, and your best attempt at a query.

  • Having issues with a left join, getting ORA-00904 error

    Ok this is something very similar to what I am facing, but dumbed down. None of these columns or tables names exist in real life (Very paranoid company I work for, understandable though) but the fundamental problem I am having is like below.
    Basically I know I could have done something similar to this is MS SQL (Or am I dreaming?). If I am right or wrong I need to know a way around this.
    Obviously if you comment out the "CAL.WEEK_SINCE_2005" and "AND CUST.week_since_2005 = CAL.WEEK_SINCE_2005" it would work. But I really need it to display the date as well. So it can be group'ed by week since 2005.
    I will be joining other statements to this. I am hoping on doing this in one select statement instead of creating multiple tables as I am now. All the other joined tables will follow a VERY similar layout to this. So something like this is need to obtain the look.
    When ran I get the following error.
    I look forward to learning what I did wrong and how I can fix it. :)
    select ORG.ORGANIZATION_NAME,
    CUST.CUST_COUNT,
    CAL.WEEK_SINCE_2005
    FROM organization ORG,
    calendar CAL
    LEFT JOIN (
    SELECT CAP.CURRENT_STORE,
    CALEN.week_since_2005,
    count(CAP.inactive_date) CUST_COUNT
    FROM CUST_AGREE_PAST CAP,
    calendar CALEN
    WHERE CAP.active_date is not null
    and CAP.inactive_code in ('T')
    and CAP.inactive_date between '01-sep-07' and sysdate
    and CAP.INACTIVE_DATE = CALEN.CALENDAR_DATE
    and CAP.RSN_CODE_ID in (select rsn_code_id from reasons where title in ('FAIL', 'NO CALL'))
    GROUP BY CAP.CURRENT_STORE,
    CALEN.week_since_2005) CUST
    ON PO.CURRENT_STORE = ORG.ORGANIZATION_NAME
    AND CUST.week_since_2005 = CAL.WEEK_SINCE_2005

    Just noticed a problem (there might be others):
    FROM organization ORG,
    calendar CAL
    LEFT JOIN (You cannot do that - you are mixing Oracle and ANSI join syntax. You have to do one or the other:
    FROM organization ORG
    JOIN calendar CAL on (ORG.col = CAL.col)
    LEFT JOIN (....)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • 3 tables with left joins - bug?

    Hello,
    i am making query where i encounter problem with left join in oracle. I am using oracle 10g and i prepare simple test case.
    he is testing tables and datas - really simple i think:
    drop table t1;
    drop table t2;
    drop table t3;
    create table t1 (a number not null);
    create table t2 (a number, b number);
    create table t3 (b number);
    insert into t3 values (1);
    insert into t3 values (2);
    insert into t3 values (3);
    insert into t1 (a) values (1);
    insert into t2 (a,b) values (1,1);
    insert into t1 (a) values (2);
    insert into t2 (a,b) values (2, null);
    insert into t1 (a) values (3);
    insert into t1 (a) values (4);
    insert into t2 (a,b) values (4,1);
    insert into t1 (a) values (5);
    insert into t2 (a,b) values (5,3);
    and now query with left joins:
    select
    t1.a
    , t2.a, t2.b
    , t3.b
    from
    t1, t2, t3
    where
    t1.a = t2.a (+)
    and t2.b = t3.b (+)
    and t3.b is null
    order by t1.a
    i get two rows as result:
    A A_1 B B_1
    2 2 null null      
    3 null null null                
    i expect these rows but when i change my query - i dont want get back t3.b column:
    select
    t1.a
    , t2.a, t2.b
    /* , t3.b*/
    from
    t1, t2, t3
    where
    t1.a = t2.a (+)
    and t2.b = t3.b (+)
    and t3.b is null
    order by t1.a
    i get only one row
    A A_1 B
    2 2 null
    My question is simple how can i only by changing columns getting back change number of returned rows? I must say i dont expect these result i expect two rows again.
    Thanks for help.

    BluShadow wrote:
    I think I know what you are getting at.
    By testing for null on t3.b when you aren't selecting the column, you are enforcing oracle to perform the join through t2 onto t1, but Oracle can't join because t2 has no matching row (although it's outer joined to t1) and therefore, for the one row it can't actually determine if t3.b is null or not, so that row can't match the conditions in a "true" sense and be displayed. If you select the column then oracle can test its nullness ok. (Perhaps this is a bug, I don't know, it's just how I know it works)If you get different results only by changing the projection part of the query this is a bug and nothing else. I can't reproduce using Oracle 10g XE, I get in both cases shown the expected two rows.
    What versions are you using to test this?
    SQL>
    SQL> select * from v$version
      2  where rownum <= 1;
    BANNER
    Oracle Database 10g Express Edition Release 10.2.0.1.0 - Product
    SQL>
    SQL> drop table t1 purge;
    Table dropped.
    SQL> drop table t2 purge;
    Table dropped.
    SQL> drop table t3 purge;
    Table dropped.
    SQL>
    SQL> create table t1 (a number not null);
    Table created.
    SQL> create table t2 (a number, b number);
    Table created.
    SQL> create table t3 (b number);
    Table created.
    SQL>
    SQL> insert into t3 values (1);
    1 row created.
    SQL> insert into t3 values (2);
    1 row created.
    SQL> insert into t3 values (3);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (1);
    1 row created.
    SQL> insert into t2 (a,b) values (1,1);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (2);
    1 row created.
    SQL> insert into t2 (a,b) values (2, null);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (3);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (4);
    1 row created.
    SQL> insert into t2 (a,b) values (4,1);
    1 row created.
    SQL>
    SQL> insert into t1 (a) values (5);
    1 row created.
    SQL> insert into t2 (a,b) values (5,3);
    1 row created.
    SQL>
    SQL> commit;
    Commit complete.
    SQL>
    SQL> select t1.a
      2       , t2.a, t2.b
      3       , t3.b
      4  from
      5         t1 left outer join t2 on (t1.a = t2.a)
      6            left outer join t3 on (t2.b = t3.b)
      7  where t3.b is null
      8  order by t1.a;
             A          A          B          B
             2          2
             3
    SQL>
    SQL> select t1.a
      2       , t2.a, t2.b
      3  --     , t3.b
      4  from
      5         t1 left outer join t2 on (t1.a = t2.a)
      6            left outer join t3 on (t2.b = t3.b)
      7  where t3.b is null
      8  order by t1.a;
             A          A          B
             2          2
             3
    SQL>Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Where clause on right side table of a left join

    I was told by someone that a where clause on the right side table of a left join is bad SQL.  I have looked around and found a great article for DB2.  I am not sure if this is 100% correct for SQL Server so would like to find a good detailed
    article on the topic.  
    Thank  you

    I was told by someone that a where clause on the right side table of a left join is bad SQL.  I have looked around and found a great article for DB2.  I am not sure if this is 100% correct for SQL Server so would like to find a good detailed
    article on the topic.  
    Thank  you
    I'm going to be blunt here so if you get offended easily please stop reading now.
    That has got to be some of the dumbest advice I've seen in a while.  Such a query serves a specific purpose, there's no good or bad to it.  Following is a classic example:
    select distinct
    CustomerID
    from Customer as c
    left join Orders as o
    on c.CustomerID = o.CustomerID
    and o.OrderDate > dateadd(day, -90, getdate())
    where o.CustomerID is null
    The above hypothetical query, which includes a where clause which targets the right table in a left join, returns all customers which have not placed an order in the past 90 days.  It's a perfectly valid query which serves a key business purpose and
    I challenge anyone to justify why they claim it is "bad SQL".
    Such a query will execute efficiently given appropriate indices.  There's simply no justification for such a blanket statement about where clauses and outer joins.

  • Left join problem

    hi guys,
    please see this query once.
    in 3rd left join i am getting error like subqueries not allowed here.
    can you help me to reslove this.
    SELECT
    '20060201'||d.acct_num as user_ref_area,
    ind.name_first||' ' ||ind.name_last AS full_name,
    PA.ADDR_FIRST_LINE,
    PA.CITY_NAME||','||
    PA.STATE_ABBR as city_state,
    PA.ZIP_CDE AS zip_cde,
    CASE WHEN iphr.pho_stat_cde ='G' THEN
    '000'||pha.pho_exchg_num||pha.pho_line_num
    ELSE '0000000000'
    END AS home_phone,
    ind.ss_num,
    d.activity_date,
    d.acct_num
    FROM (
    select j.acct_num,j.activity_date
    from (
    select dxr.acct_num,
    to_char(o3.o3bfct) as activity_date
    from debtp.o3
    JOIN debtp.acct_xref dxr
    ON o3.o3e5cd = dxr.e5cd
    WHERE o3dhce in ('aj','ja','ta')
    AND load_dt >=to_date('2006/01/28','yyyy/mm/dd')-- trunc(sysdate-4) --NEED TO USE SYSDATE-4                                        
    UNION
    select account_number,TO_CHAR(data_date, 'YYYYMMDD') as activitydate
    from clctdm.triad_history
    where data_date =to_date('2006/01/31','yyyy/mm/dd')--trunc(sysdate-1) --NEED TO USE SYSDATE-1
    and delq_coll_ind in ('960','961','962','963')
    ) j
    left join
    select ACCT_NUM
    from hbivt1.pp_fd_accts FDAI
    where FDAI.DATE_activity >='20060102'--to_char(trunc(add_months(sysdate,-1)),'yyyymmdd')
    ) k
    on j.acct_num =k.acct_num
    where k.acct_num IS null
    ) d
    JOIN AUTOR3.ACCT_XREF XR --lookup for arr_id_acct values
    ON d.acct_num =xr.acct_num
    JOIN AUTOR3.ARR_IP_POSTL_REL AIPL --lookup for postl_addr_id
    ON AIPL.ARR_ID = XR.ARR_ID_ACCT
    and aipl.actv_ind ='0'
    join autor3s.indv ind --table with values for FIRSTDATA
    on aipl.hi_num =ind.hi_num_indv
    Left JOIN AUTOR3s.POSTL_ADDR PA ----table with values for FIRSTDATA
    ON aipl.POSTL_ADDR_ID = PA.POSTL_ADDR_ID
    left join autor3.ip_pho_rel iphr
    on iphr.hi_num =aipl.hi_num and
    start_dt_tm =(
    select max(iphr2.start_dt_tm) as start_dt_tm from AUTOR3.IP_PHO_REL IPHR2
    WHERE iphr2.rank_num='1'
    and iphr2.ip_pho_rel_cde='001000'
    and iphr2.actv_ind='0'
    and iphr2.hi_num =aipl.hi_num
    )

    Oracle only supports outer joins as extended equalities.
    You'll have to use the syntax:
    FROM PC2KAUDIT,AUDITDETAIL
    WHERE
    ... (other where clause)
    AND
    PC2KAUDIT.AUDITID = AUDITDETAIL.AUDITID (+)
    This will do basically the same thing. Unfortunately there is no common syntax, unless oyu have a fancy ODBC driver, which might do this translation for you.
    null

  • Multi-Left Join Query Tuning

    I am tuning a SELECT query with 36 Left Joins in addition to normal Inner Joins and a View.
    I have used the RESULT_CACHE hint with some success.
    I have tried the LEADING hint and USE_MERGE with no success.
    Is there an Undocumented HINT and that may assist me?
    Thanks
    BRAD

    Hi, Brad,
    Welcome to the forum!
    970109 wrote:
    I am tuning a SELECT query with 36 Left Joins in addition to normal Inner Joins and a View.Why does the query need so many outer joins? Could there be a bad table design behind this problem? Post a simplified version ot the problem (with maybe 3 tables that need to be outer-joined). Post CREATE TABLE and INSERT statements for a little sample data (relevant columns only), the results you want from that sample data, and an explanation of how you get those results from that data.
    See the forum FAQ {message:id=9360002}
    For all tuning problems, see {message:id=9360003}

  • Improve performance when using lots of left join

    when i run this query, it is taking *27 minutes* to execute. all keys have index. please help me to improve performance. i am using 11g.
    select distinct com.m1co as CO_ID,
    fsr.policy_number as POL_ID,
    com.M1AGNM as AGNCY_ID,
    cr.agent_code as AGT_ID,
    P.full_name as agent_name,
    ia.status_description as STS_CD,
    to_char(ia.bound_date, 'MM/DD/YYYY') as POL_INFC_DT,
    (fchgmm||'/'||fchgdd||'/'||fchgyy) as PAY_UP_DT ,
    (mcpdtm||'/'||mcpdtd||'/'||mcpdty) as pay_to_dt,
    (fexpmm||'/'||fexpdd||'/'||fexpyy) as MATURE_DT,
    ia.BILLING_FREQUENCY as PAY_MODE_CD,
    casc.MCPYCD as PAY_METHOD_CD,
    casc.MCPRMM as MODAL_PREM_AMT,
    casc.MCCRCD as POL_CUR,
    casc.MCNOPT as NFO_CD,
    cas.FINSTP as LINE_OF_BUSS,
    (MCPDTM||'/'||MCPDTD||'/'||MCPDTY) as BILL_TO_DT,
    com.M1LOCA as COLL_OFF,
    to_char(ia.bound_date, 'MM/DD/YYYY') as DELIVERY_DT,
    P.FULL_NAME as Serv_AGENT_NAME,
    casm.MWAGTN as SERV_AGT_CD,
    casc.MCNOPT as NFO_RULE,
    ia.STATUS_DESCRIPTION as POL_CSTAT_REASN_CD,
    SUBSTR(datesplit5(datesub),1,10) as APP_RECV_DT,
    to_char(ia.bound_date, 'MM/DD/YYYY') as ISSUE_DT,
    ia.SUM_ASSURED as CVG_FACE_AMT,
    p.IDENTITY_CARD_NUMBER as INSRD_CLI_CD
    FROM financial_services_role fsr
    left join channel_role cr on fsr.role_player_id=cr.role_player_id
    left join person p on (fsr.role_player_id=p.role_player_id and FSR.TYPE_DESCRIPTION IN ('AG','AGT'))
    left join ext_lsp_comagtm1 com on cr.agent_code=com.m1agno
    left join individual_agreement ia on fsr.policy_number =
    DECODE(ia.Business_Key_Contract_Number, NULL, ia.Business_Key_Policy_Number,ia.Business_Key_Contract_Number)
    left join EXT_LSP_CASCNTRM casc on (fsr.policy_number = casc.MCCNTR)
    left join ext_lsp_casbene cas on (fsr.policy_number = cas.fpolno and fbrcd = 0 )
    left join ext_lsp_casmwagt casm on (fsr.policy_number = casm.mwpoln and com.m1agnm = 'TAN')
    left join cdmtgt.EXT_LA_PTRNPF on (chdrnum = fsr.policy_number and
    BATCTRCDE = 'T600')
    WHERE com.m1co = 'IL';
    Thank you
    Edited by: 1000228 on Jun 5, 2013 10:36 AM

    HOW To Make TUNING request
    SQL and PL/SQL FAQ
    SELECT DISTINCT com.m1co                             AS CO_ID,
                    fsr.policy_number                    AS POL_ID,
                    com.m1agnm                           AS AGNCY_ID,
                    cr.agent_code                        AS AGT_ID,
                    ' '                                  AS AGNCY_ID_2,
                    ' '                                  AS AGT_ID_2,
                    ' '                                  AS AGT_ID_2_NAME,
                    P.full_name                          AS agent_name,
                    ia.status_description                AS STS_CD,
                    To_char(ia.bound_date, 'MM/DD/YYYY') AS POL_INFC_DT,
                    ( fchgmm
                      ||'/'
                      ||fchgdd
                      ||'/'
                      ||fchgyy )                         AS PAY_UP_DT,
                    ( mcpdtm
                      ||'/'
                      ||mcpdtd
                      ||'/'
                      ||mcpdty )                         AS pay_to_dt,
                    ( fexpmm
                      ||'/'
                      ||fexpdd
                      ||'/'
                      ||fexpyy )                         AS MATURE_DT,
                    ia.billing_frequency                 AS PAY_MODE_CD,
                    casc.mcpycd                          AS PAY_METHOD_CD,
                    casc.mcprmm                          AS MODAL_PREM_AMT,
                    casc.mccrcd                          AS POL_CUR,
                    casc.mcnopt                          AS NFO_CD,
                    cas.finstp                           AS LINE_OF_BUSS,
                    ' '                                  AS REGLR_OR_SCHEDL_TOPUP,
                    ' '                                  AS POLICY_LAPSED_DT,
                    ( mcpdtm
                      ||'/'
                      ||mcpdtd
                      ||'/'
                      ||mcpdty )                         AS BILL_TO_DT,
                    com.m1loca                           AS COLL_OFF,
                    To_char(ia.bound_date, 'MM/DD/YYYY') AS DELIVERY_DT,
                    P.full_name                          AS Serv_AGENT_NAME,
                    casm.mwagtn                          AS SERV_AGT_CD,
                    casc.mcnopt                          AS NFO_RULE,
                    ia.status_description                AS POL_CSTAT_REASN_CD,
                    Substr(Datesplit5(datesub), 1, 10)   AS APP_RECV_DT,
                    To_char(ia.bound_date, 'MM/DD/YYYY') AS ISSUE_DT,
                    ia.sum_assured                       AS CVG_FACE_AMT,
                    '0'                                  AS BASE_CVG_NUM,
                    p.identity_card_number               AS INSRD_CLI_CD
    FROM   financial_services_role fsr
           left join channel_role cr
                  ON fsr.role_player_id = cr.role_player_id
           left join person p
                  ON ( fsr.role_player_id = p.role_player_id
                       AND FSR.type_description IN ( 'AG', 'AGT' ) )
           left join ext_lsp_comagtm1 com
                  ON cr.agent_code = com.m1agno
           left join individual_agreement ia
                  ON fsr.policy_number = Decode(ia.business_key_contract_number,
                                         NULL,
           ia.business_key_policy_number,
                                         ia.business_key_contract_number)
           left join ext_lsp_cascntrm casc
                  ON ( fsr.policy_number = casc.mccntr )
           left join ext_lsp_casbene cas
                  ON ( fsr.policy_number = cas.fpolno
                       AND fbrcd = 0 )
           left join ext_lsp_casmwagt casm
                  ON ( fsr.policy_number = casm.mwpoln
                       AND com.m1agnm = 'TAN' )
           left join cdmtgt.ext_la_ptrnpf
                  ON ( chdrnum = fsr.policy_number
                       AND batctrcde = 'T600' )
    WHERE  com.m1co = 'IL';

  • Doubt Regarding LEFT JOIN Operation

    Hello,
    With the Old syntax in place it is easier for find that which join is performed on which table ...
    But with the new syntax ..m getting bit confused when INNER & LEFT JOINS used together ...
    Below is the FROM clause ...please explain .. how this JOIN is gonna take place ..& which table is Left joined with whom...
    FROM VW_TRANS_MANAGER_SALES ref_1
    LEFT OUTER JOIN VW_AGREE_ASSIGN_TAG_DTLS ass
    ON Trim(ass.agreement_id) = trim(ref_1.AGREEMENT_ID)
    LEFT OUTER JOIN VW_CURENT_RATING_DTLS CURR
    ON (ref_1.company_code =curr.COMPANYCODE)
    LEFT OUTER JOIN VW_PREV_RATING_DETAILS PREV
    ON (ref_1.company_code =prev.COMPANYCODE)
    LEFT OUTER JOIN CRMADMIN.CO_MA_COMPANY_CONTACTS cont
    ON (ref_1.CLIENT_CONTACT_ID= cont.CONTACT_ID)
    LEFT OUTER JOIN CRMADMIN.COR_CRM_MST_CITY city
    ON (city.City_id= cont.City_id))
    ---------------------------------------------------------------------------------------------------------------------------------------

    Hi,
    Aijaz Mallick wrote:
    Yeah .. but was a bit Confusing as u used 2 columns in each table....
    Doesn't it depends on the joining condition we use ... lets Say ..if i use an INNER join after 2 LEFT join ... & m doing an that inner join with the first SOURCE table .... then will it perform a join on the resultset on the previous Joins...???Sorry, I'm not sure what you're asking.
    Please post a specific example of a join that you don't understand, or some results that you don't know how to get.
    Use commonly available tables (like those in the scott or hr schemas) or post your own CREATE TABLE and INSERT statements.
    Using ANSI syntax, the results are as if the joins were done in the order they appear in the FROM clause (even though the optimizer may not actually do them in that order).
    For example, in the querry below, the inner-join between emp and salgrade is done first, then the outer join with dept is done to that result set.
    SELECT     d.dname
    ,     e.ename
    ,     g.losal
    FROM          scott.emp     e
    JOIN          scott.salgrade     g     ON     e.sal     BETWEEN     g.losal
                                       AND     g.hisal
    RIGHT OUTER JOIN  scott.dept     d     ON     e.deptno     = d.deptno
    ;Output:
    DNAME          ENAME           LOSAL
    ACCOUNTING     CLARK            2001
    ACCOUNTING     MILLER           1201
    ACCOUNTING     KING             3001
    RESEARCH       FORD             2001
    RESEARCH       SCOTT            2001
    RESEARCH       JONES            2001
    RESEARCH       ADAMS             700
    RESEARCH       SMITH             700
    SALES          BLAKE            2001
    SALES          ALLEN            1401
    SALES          MARTIN           1201
    SALES          WARD             1201
    SALES          JAMES             700
    SALES          TURNER           1401
    OPERATIONSNotice that the OPERATIONS department, which has no matches in the other tables, is still included because of the outer join.
    If you want to have the joins done in a different order, you can explicitly join some table first, either in a sub-query or just by grouping joins within parentheses in the same FROM clause, as in the query below (which produces the same results as the query above):
    SELECT     d.dname
    ,     e.ename
    ,     g.losal
    FROM          scott.dept     d
    LEFT OUTER JOIN     (     -- Join the following tables first:
                   scott.emp     e
              JOIN     scott.salgrade     g     ON     e.sal     BETWEEN     g.losal
                                            AND     g.hisal
              )     ON     d.deptno     = e.deptno
    ;

  • JPA and LEFT JOIN

    I have a very basic question related to JPA.
    I am using dict tables and connecting it to MaxDB.
    In my Entity I have a select statement like this,
    @NamedQuery  (name = "getOperations", query = "SELECT operT.id FROM SII_ARC_Oper operT " +
                   "LEFT JOIN SII_ARC_Service serviceT " +
                   "ON   operT.sid = serviceT.sid AND " +
                   "serviceT.duuid =:duuid")
    When I call this in my Bean, I get this error,
    An error occurred processing the named query >>getOperations<< with the query string >>SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN SII_ARC_Service serviceT ON   operT.sid = serviceT.sid AND serviceT.duuid =:duuid<<. The exception text is: line 1: Variable 'SII_ARC_Service' not declared
    SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN SII_ARC_Service serviceT ON   operT.sid = serviceT.sid AND serviceT.duuid =:duuid
                                                      ^
    line 1: unexpected token: serviceT
    SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN SII_ARC_Service serviceT ON   operT.sid = serviceT.sid AND serviceT.duuid =:duuid
    I am just wondering how do I declare the u201CSII_ARC_Serviceu201D in my Entity before the Named Query. Or am I not declaring anything else..?
    Thanks
    Domnic
    Edited by: domnic savio on Jul 21, 2008 12:16 PM

    I have some improvements now although the problem is not solved yet,
    I have the JPQL as
    // The Named Query
    @NamedQuery  (name = "getOperations", query = "SELECT oper.id FROM SII_ARC_Oper oper " +
                   "LEFT JOIN oper.service serviceT " +
                   "WHERE serviceT.duuid =:duuid")
    // The many to one relationship
    @Column(name= "SERVICE_TABLE")
         @ManyToOne(targetEntity=com.sap.sii.archeiver.SII_ARC_Service.class)
         @JoinColumn(referencedColumnName = "SID")
         private SII_ARC_Service service;
    On calling the NamedQuery and passing a parameter, I get the error,
    Errors have occurred during the precompilation of named queries:
    An error occurred processing the named query >>getOperations<< with the query string >>SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN operT.service serviceT WHERE serviceT.duuid =:duuid<<. The exception text is: line 1: Path 'opert.service' is not association path.
    SELECT operT.id FROM SII_ARC_Oper operT LEFT JOIN operT.service serviceT WHERE serviceT.duuid =:duuid
    1) What association path does the compiler refer too !?!.
    2) Is the JPQL Querry valid without an ON clause ?!.
    anyone has an idea..!?!
    thanks in advance
    Domnic

Maybe you are looking for

  • Select Expert Drop down list

    Post Author: MarcS CA Forum: General Hi, I'm using Crystal Report 11. I'm creating a parameter field that will allow me to select a specific data from one field in my database.  When I use the "Select Expert" it only show me the first 500 records.  H

  • Audit who did or tried to run reports on certain criterias and when?

    Hi, Where can I find more information on Security in BPC? I´d like to know more about on how to audit users, is there any standard reports that can show me who ran reports, which critera, which time etc.? Thanks!

  • Data filtering for table and chart

    Hi, I'm new to crystal reports XI. I have one sql query which I am using as the data source for a chart and a table (cross tab). The query return balance for monthly data. In the chart I need to display all the data returned by the query. In the tabl

  • Trouble emailing from Photos for Mac

    I'm having trouble mailing photos from Photos for Mac. When I go to the share icon Mail doesn't appear as an option as it did in iPhoto. Am I missing something?

  • Can't save movie captures to server...only to client

    l have iMovie 11 (9.0) on a 10.6.8 client.  I can't save movie clips to the server, but can save to the client. When I try to "File->Import from camera" (local iSight), then "capture", on the dialog that pops up I see "Save To:" with three shares: 1)