LEFT JOINING with a string?

I'm viewing code where the person left joined a column with a string.
   lu_ods.lookup_type(+) = 'FORX_ORDERPRO_ACTION'Is this just bad coding. Is there any reason why someone would do this?
Doesn't
   lu_ods.lookup_type = 'FORX_ORDERPRO_ACTION'work just as well?

As Sentinel said, it can change the result if you are left joining between two tables:
with a as (
select 1 num, 'a' col from dual UNION ALL
select 2 num, 'b' col from dual UNION ALL
select 3 num, 'c' col from dual
b as (
select 1 num, 'a' col from dual UNION ALL
select 4 num, 'e' col from dual UNION ALL
select 5 num, 'f' col from dual
select *
from a, b
where a.num(+) = b.num
  and a.num(+) = 1;
NUM                    COL NUM                    COL
1                      a   1                      a  
                           5                      f  
                           4                      e  
3 rows selectedWithout the left join on the number, we lose results:
with a as (
select 1 num, 'a' col from dual UNION ALL
select 2 num, 'b' col from dual UNION ALL
select 3 num, 'c' col from dual
b as (
select 1 num, 'a' col from dual UNION ALL
select 4 num, 'e' col from dual UNION ALL
select 5 num, 'f' col from dual
select *
from a, b
where a.num(+) = b.num
  and a.num = 1;
NUM                    COL NUM                    COL
1                      a   1                      a  
1 rows selected

Similar Messages

  • Oracle 8i, left join with conditional

    Coming from the MySQL world, I'm trying to do a left join with a
    condition:
    select c.givenname,c.surname,c.userid,r.letternr
    from cand c,responses r
    where (c.userid=r.username(+))
    and
    c.activeprofile=1
    No problem whatsoever.
    If there is no corresponding "response" in R for a given
    candidate, I get a NULL return for R.letternr.
    However, there is a flag in R, called "VISIBLE" that I wish to
    use to mean "Don't count this entry in R". R.VISIBLE=0 means
    that the response is not active/present/visible/valid.
    Am I making any sense? :-)

    If you don't want to display a row with a null value for
    r.letternr when r.visible = 0, then:
    SELECT     c.givenname,
               c.surname,
               c.userid,
               r.letternr
    FROM       cand c,
               responses r
    WHERE      c.userid = r.username (+)
    AND        c.activeprofile = 1
    AND        r.visible != 0
    Or, if you do want to display a row with a null value for
    r.letternr when r.visible = 0, then:
    SELECT     c.givenname,
               c.surname,
               c.userid,
               r.letternr
    FROM       cand c,
               responses r
    WHERE      c.userid = r.username (+)
    AND        c.activeprofile = 1
    AND        r.visible (+) != 0

  • JPA Criteria : LEFT JOIN with an AND condition

    Hi all,
    I have a question regarding JPA criteria.
    Here is my JPA query :
    CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
    CriteriaQuery<Long> criteriaQuery = criteriaBuilder.createQuery(Long.class);
    Root<Email> emailRoot = criteriaQuery.from(Email.class);
    criteriaQuery.distinct(true);
    Predicate globalCondition = criteriaBuilder.equal(emailRoot.get(Email_.type), EmailType.in);
    Predicate responseMandatoryCondition = criteriaBuilder.equal(emailRoot.get(Email_.responseMandatory), true);
    Predicate typeCondition = criteriaBuilder.notEqual(emailRoot.join(Email_.emailsOut, JoinType.LEFT).get(Email_.responseType),ResponseType.response);
    globalCondition = criteriaBuilder.and(globalCondition, responseMandatoryCondition);
    globalCondition = criteriaBuilder.and(globalCondition, typeCondition);
    em.createQuery(mainCriteria.where(globalCondition)).getSingleResult();
    Here is the result of this query :
    SELECT DISTINCT email0_.ID AS col_0_0_
    FROM EMAIL email0_
    LEFT OUTER JOIN email emailso1_ ON email0_.ID = emailso1_.ID_EMAIL_IN
    WHERE email0_.TYPE = 'in'
    AND email0_.RESPONSE_MANDATORY = true
    AND emailso1_.RESPONSE_TYPE <> 'response'
    LIMIT 0 , 30
    And here is the request I needed :
    SELECT DISTINCT email0_.ID AS col_0_0_
    FROM EMAIL email0_
    LEFT OUTER JOIN email emailso1_ ON email0_.ID = emailso1_.ID_EMAIL_IN AND emailso1_.RESPONSE_TYPE <> 'response'
    WHERE email0_.TYPE = 'in'
    AND email0_.RESPONSE_MANDATORY = true
    LIMIT 0 , 30
    As you can see I need to check if the RESPONSE_TYPE is equals on the same line that the LEFT OUTER JOIN. Does anybody know how to write such an JPA criteria query ?
    Thanks ,
    Louis
    Edited by: user13105928 on 17 févr. 2011 03:06

    You cannot define an ON clause with Criteria, nor JPQL.
    Perhaps you can reword the query to avoid needing an ON clause.
    What is the query you want to do (in english)?
    Can you just use an OR in the where clause?
    There is a enhancement request to have ON clause support added, please vote for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=312146
    James : http://www.eclipselink.org

  • Whats the alternate for left join with using IN operator in the where claus

    My senario...
    Select t1.f1, t1.f2, t2.f3
      From t1, t2
    Where ...
          t1.f1> (+) IN t2.f1
          ...alternate query..
    Select t1.f1, t1.f2, t2.f3
      From t1, t2
    Where ...
          (t1.f1> IN t2.f1 or 1=1)
          ...will the alternate query satisfy the above senario..?

    I'm not quite sure I've understood what the OP's question is, but will ANSI syntax deal with it?
    SQL> ed
    Wrote file afiedt.buf
      1  with a as (select 1 as num, 2 as data from dual union all
      2             select 2 as num, 3 as data from dual union all
      3             select 3 as num, 4 as data from dual),
      4       b as (select 1 as num, 5 as data from dual union all
      5             select 3 as num, 7 as data from dual)
      6  -- END OF TEST DATA
      7  select a.num, a.data, b.data
      8* from a LEFT OUTER JOIN b ON (a.num = b.num AND b.num IN (3))
    SQL> /
           NUM       DATA       DATA
             3          4          7
             1          2
             2          3
    SQL>

  • Inconsistent results with ANSI LEFT JOIN on 9iR2

    Is this a known issue? Is it solved in 10g?
    With the following data setup, I get inconsistent results. It seems to be linked to the combination of using LEFT JOIN with the NULL comparison within the JOIN.
    create table titles (title_id int, title varchar(50));
    insert into titles values (1, 'Red Book');
    insert into titles values (2, 'Yellow Book');
    insert into titles values (3, 'Blue Book');
    insert into titles values (4, 'Orange Book');
    create table sales (stor_id int, title_id int, qty int, email varchar(60));
    insert into sales values (1, 1, 1, '[email protected]'));
    insert into sales values (1, 2, 1, '[email protected]');
    insert into sales values (3, 3, 4, null);
    insert into sales values (3, 4, 5, '[email protected]');
    SQL&gt; SELECT titles.title_id, title, qty
    2 FROM titles LEFT OUTER JOIN sales
    3 ON titles.title_id = sales.title_id
    4 AND stor_id = 3
    5 AND sales.email is not null
    6 ;
    TITLE_ID TITLE QTY
    4 Orange Book 5
    3 Blue Book
    1 Red Book
    2 Yellow Book
    SQL&gt;
    SQL&gt; SELECT titles.title_id, title, qty
    2 FROM titles LEFT OUTER JOIN sales
    3 ON titles.title_id = sales.title_id
    4 AND 3 = stor_id
    5 AND sales.email is not null;
    TITLE_ID TITLE QTY
    2 Yellow Book 1
    4 Orange Book 5
    3 Blue Book
    1 Red Book
    It seems to matter what order I specify the operands stor_id = 3, or 3 = stor_id.
    In the older (+) environment, I would understand this, but here? I'm pretty sure most other databases don't care about the order.
    thanks for your insight
    Kevin

    Don't have a 9i around right now to test ... but in 10 ...
    SQL> create table titles (title_id int, title varchar(50));
     
    Table created.
     
    SQL> insert into titles values (1, 'Red Book');
     
    1 row created.
     
    SQL> insert into titles values (2, 'Yellow Book');
     
    1 row created.
     
    SQL> insert into titles values (3, 'Blue Book');
     
    1 row created.
     
    SQL> insert into titles values (4, 'Orange Book');
     
    1 row created.
     
    SQL> create table sales (stor_id int, title_id int, qty int, email varchar(60));
     
    Table created.
     
    SQL> insert into sales values (1, 1, 1, '[email protected]');
     
    1 row created.
     
    SQL> insert into sales values (1, 2, 1, '[email protected]');
     
    1 row created.
     
    SQL> insert into sales values (3, 3, 4, null);
     
    1 row created.
     
    SQL> insert into sales values (3, 4, 5, '[email protected]');
     
    1 row created.
     
    SQL> SELECT titles.title_id, title, qty
      2   FROM titles LEFT OUTER JOIN sales
      3   ON titles.title_id = sales.title_id
      4   AND stor_id = 3
      5   AND sales.email is not null
      6   ;
     
      TITLE_ID TITLE                                                     QTY
             4 Orange Book                                                 5
             3 Blue Book
             1 Red Book
             2 Yellow Book
     
    SQL>
    SQL> SELECT titles.title_id, title, qty
      2   FROM titles LEFT OUTER JOIN sales
      3   ON titles.title_id = sales.title_id
      4   AND 3 = stor_id
      5   AND sales.email is not null;
     
      TITLE_ID TITLE                                                     QTY
             4 Orange Book                                                 5
             3 Blue Book
             1 Red Book
             2 Yellow Book
    SQL> exit
    Disconnected from Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Production
    With the Partitioning, OLAP and Data Mining options

  • Wrap a store procedure which include "Left Join"

    In 9i, i write a store procedure :
    CREATE OR REPLACE PROCEDURE
    get_code(STATION_NUM IN VARCHAR2,COMMAND1 OUT VARCHAR2) AS
    BEGIN
    SELECT A.*, B.XX
    FROM A LEFT JOIN B ON A.ID = B.ID
    WHERE A.STATION_NUM = STATION_NUM
    END;
    AND, I wrap this store procedure, it show error message:
    PSU(103,1,50,41):Encountered the symbol "LEFT" when expecting one of the following:
    , ; for group having intersect minus order start union where
    connect
    Why i can run this store procedure, but can't wrap it?
    my oracle is 9.2.0.1.0

    Replace Left Join with "," and put "(+)" symbol after A.ID
    Regds,
    Balaji

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

  • T-sql 2008 r2 cte join with a second table

    In a sql server 2008 r2 database, I am trying to take the results of the cte called sProgram and join the results with the Person table in the query. The syntax of the join looks ok, however the results of the join are incorrect. The joined results are null
    when there is really data that can be joined. Can you tell me how to join the query so the results of the sprogram cte will be joined to the Person table correctly?
    1. Here is the query:
    ;with  sProgram as (
    SELECT   [personID],[attributeID],[value], [date],ROW_NUMBER() OVER(Partition by[personID] ORDER BY [personID],[date] DESC) rn
    FROM [dbo].[CustomS]
    where  [attributeID] in ('562','563','564','565')
    ,programSelect as
    select [personID],[attributeID],[value],[date]
    from sProgram
    where rn=1
    SELECT person.personID  
     , cs562.personID
     , cs562.attributeID
     , cs562.value
     , cs562.[date]
     , cs563.personID
     , cs563.attributeID
     , cs563.value
     , cs563.[date] 
     , cs564.personID
     , cs564.attributeID
     , cs564.value
     , cs564.[date]
     , cs565.personID
     , cs565.attributeID
     , cs565.value
     , cs565.[date]     
    FROM Person  cs562   
    join programSelect  on  cs562.personID  = Person.personID  and  cs562.attributeID= '562'
    left join programSelect cs563 on cs563.personID = cs562.personID and cs563.[Date] = cs562.[date] and cs563.attributeID ='563'
    left join programSelect  cs564 on cs564.personID = cs563.personID and  cs564.[date] = cs563.[Date] and cs564.attributeID ='564'
    left join programSelect cs565 on cs565.personID = cs564.personID and cs565.[Date] = cs564.[date] and cs565.attributeID ='565'
    GROUP BY 
    person.personID  
     , cs562.personID
     , cs562.attributeID
     , cs562.value
     , cs562.[date]
     , cs563.personID
     , cs563.attributeID
     , cs563.value
     , cs563.[date] 
     , cs564.personID
     , cs564.attributeID
     , cs564.value
     , cs564.[date]
     , cs565.personID
     , cs565.attributeID
     , cs565.value
     , cs565.[date] 
    2. here is the CustomS table with some data.
     SELECT [CustomSID]
           ,[personID]    
           ,[attributeID]
           ,[value]
           ,[date]
       FROM [dbo].[CustomS]
       where personID=7170
       and attributeID in (562,563,564,565)
       order by date desc
    CustomSID personID        attributeID      value          [date]
     262490684  7170              562          GA         2013-08-14 07:26:00
     262490683   7170              565          05/23/2014 2013-08-14 07:26:00
     262490682   7170              563           Acd         2013-08-14 07:26:00
     262490681   7170              564          08/14/2013 2013-08-14 07:26:00
     251784         7170         564          09/06/2007 2007-09-08 00:00:00
     250029         7170         562          MA         2007-09-08 00:00:00
     248287         7170         563          asp         2007-09-08 00:00:00
     251785         7170         564          09/07/2006 2006-09-08 00:00:00
     248286         7170         563          asp         2006-09-08 00:00:00
     250028         7170         562          MA         2006-09-08 00:00:00
     251783         7170         564          09/06/2006 2006-09-06 00:00:00
     249367         7170         562          LA         2006-09-06 00:00:00
     248285         7170         563          asp         2006-09-06 00:00:00
    3. Here is the table definition:
     here is the table definition:
    alter TABLE [dbo].[CustomS](
      [CustomSID] [int] IDENTITY(1,1) NOT NULL,
      [personID] [int] NOT NULL,
      [attributeID] [int] NOT NULL,
      [value] [varchar](256) NULL,
      [date] [smalldatetime] NULL,

    Partition by CustomsID will didvide data into groups based on CustomsID value.
    ROW_NUMBER will generate sequence numbers over the group and when you look for rn=1 you'll get record with latest group
    Also from what I understand you need just this instead of all those left joins
    ;with sProgram as (
    SELECT [personID],[attributeID],[value], [date],
    ROW_NUMBER() OVER(Partition by [personID],[attributeID] ORDER BY [date] DESC) rn
    FROM [dbo].[CustomS]
    where [attributeID] in ('562','563','564','565')
    SELECT p.personID
    , pr.personID , pr.attributeID , pr.value , pr.[date]
    , pr1.*
    FROM Person p
    left join sProgram pr
    on pr.personID = p.personID
    and pr.Rn = 1
    and attributeID = '562'
    outer apply (SELECT personID,
    max(case when attributeID = '563' then attributeID end) as AttrID563,
    max(case when attributeID = '563' then value end) as Value563,
    max(case when attributeID = '563' then date end) as date563,
    max(case when attributeID = '564' then attributeID end) as AttrID564,
    max(case when attributeID = '564' then value end) as Value564,
    max(case when attributeID = '564' then date end) as date564,
    max(case when attributeID = '565' then attributeID end) as AttrID565,
    max(case when attributeID = '565' then value end) as Value565,
    max(case when attributeID = '565' then date end) as date565
    where personID = p.PersonID
    and [date] = pr.[date]
    and Rn = 1
    group by personId)pr1
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Testing for IS NOT NULL with left join tables

    Dear Experts,
    The query is showing the NULL rows in the query below....
    Any ideas, advice please? tx, sandra
    This is the sql inspector:
    SELECT O100321.FULL_NAME_LFMI, O100321.ID, O100404.ID, O100321.ID_SOURCE
    , O100404.NAME, O100321.PERSON_UID, O100404.PERSON_UID, O100404.VISA_TYPE
    FROM ODSMGR.PERSON O100321
    , ODSMGR.VISA O100404
    WHERE ( ( O100321.PERSON_UID = O100404.PERSON_UID(+) ) ) AND ( O100404.VISA_TYPE(+) IS NOT NULL )

    Hi Everyone,
    I am understanding alot of what Michael and Rod wrote.... I am just puzzled over the following:
    the query below is left joining the STUDENT table to
    HOLD table.
    The HOLD table - contains rows for students who have holds on their record.
    a student can have more than one hold (health, HIPAA, basic life saving course)
    BUT, for this query: I'm only interested that a hold exists, so I'm choosing MAX on hold desc.
    Selecting a MAX, helps me, bec. it reduces my join to a 1 to 1 relationship, instead of
    1 to many relationship.
    Before I posted this thread at all, the LEFT JOIN below testing for IS NOT NULL worked w/o
    me having to code IS NOT NULL twice....
    Is that because, what's happening "behind the scenes" is that a temporary table containing all max rows is being
    created, for which Discoverer has no predefined join instructions, so it's letting me do a LEFT JOIN and have
    the IS NOT NULL condition.
    I would so appreciate clarification. I have a meeting on Tues, for which I have to explain LEFT JOINS to the user
    and how they should create a query. I need to come up with rules.
    If I feel "clear", I asked my boss to buy Camtasia videocast software to create a training clip for user to follow.
    Also, if any Banner user would like me to email the DIS query to run on their machine, I would be glad to do so.
    thx sooo much, Sandra
    SELECT O100384.ACADEMIC_PERIOD, O100255.ID, O100384.ID, O100255.NAME, O100384.NAME, O100255.PERSON_UID, O100384.PERSON_UID, MAX(O100255.HOLD_DESC)
    FROM ODSMGR.HOLD O100255, ODSMGR.STUDENT O100384
    WHERE ( ( O100384.PERSON_UID = O100255.PERSON_UID(+) ) ) AND ( O100384.ACADEMIC_PERIOD = '200820' )
    GROUP BY O100384.ACADEMIC_PERIOD, O100255.ID, O100384.ID, O100255.NAME, O100384.NAME, O100255.PERSON_UID, O100384.PERSON_UID
    HAVING ( ( MAX(O100255.HOLD_DESC(+)) ) IS NOT NULL )
    ORDER BY O100384.NAME ASC

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

  • Simple left-join doesn't work. error with: Unknown column

    Hi guys,
    can anyone assist on this simple query:
    SELECT D.* , SUM( TD.debit_amount), SUM(TAP.amount)
    FROM debit AS D, transaction_debit AS TD
    LEFT JOIN TA_PAYMENTS AS TAP ON D.debit_id=TAP.debit_id
    WHERE D.debit_id = TD.debit_id
    GROUP BY TD.debit_idThe error message I receive is:
    #1054 - Unknown column 'D.debit_id' in 'on clause' I'm trying to relate 3 tables (debit, transactions-debit and ta_payment), some payment may not exist so therefore i use left join.
    thanks for any pointers

    SELECT D.* , SUM( TD.debit_amount), SUM(TAP.amount)
    FROM debit AS D, transaction_debit AS TD
    LEFT JOIN TA_PAYMENTS AS TAP ON
    D.debit_id=TAP.debit_id
    WHERE D.debit_id = TD.debit_id
    GROUP BY TD.debit_id
    I'm trying to relate 3 tables (debit,
    transactions-debit and ta_payment), some payment may
    not exist so therefore i use left join.You are trying to mix "the older join syntax", with the join condition in the where-clause, with "the new join syntax", with the join condition in the "on-clause", which I think is causing trouble.
    How about using only "the new syntax":
    SELECT D.* , SUM( TD.debit_amount), SUM(TAP.amount)
    FROM debit AS D JOIN transaction_debit AS TD on (D.debit_id = TD.debit_id)
         LEFT JOIN TA_PAYMENTS AS TAP ON (D.debit_id=TAP.debit_id)
    GROUP BY TD.debit_idDoes that help?

  • 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

  • How to make a customize form with optional parameter and left join

    Hi,
    I am trying to make a report with a left join. I also want ot have optional parameters in it.
    I am using the Create Reports From SQL Query method:
    SQL is :
    select ename, sal
    from scott.emp left join scott.dept
    on scott.emp.deptno = scott.dept.deptno
    where sal >= :lower_sal
    and sal <= :higher_sal;
    However, if I do it this way, I those 2 parameters are not optional.... How can I make them optional?
    If I use the Create Reports From Query Wizard method, I can make the parameters optional, but then I cannot do the left join...
    Thanks,
    Wilson

    hi,
    to catch null values on both sides I use:
    where nvl(sal,0) >= nvl(:lower_sal,nvl(sal,0))
    and nvl(sal,0) <= nvl(:higher_sal,9999999999)
    otherwise there will be no rows in the report where the value of sal is null, even if there are no selection criteria entered.
    regards Michael

  • Left join query with join of three tables

    I'm trying to build a query which has me stumped. Most of the query is fairly straightforward but I've run into an issue I'm not sure how to solve.
    Background:
    We have actions stored in i_action.
    We have the available attributes for each type of action. The available attributes for each action are described in shared_action_attribute. Each type of action may have up to three attributes or none at all.
    We have the values stored for the attributes in i_attribute_value.
    A written example:
    We have a transfer action (action_code B4). The entry of the B4 action into i_action records the fact that the transfer occurred and the date on which it occurred. The available attributes for a transfer action are the receiving function code, the receiving unit number, and the transfer reason code. These available attribute types and their order are stored in shared_action_attribute. The actual values of the attributes for a specific transfer action are stored in i_attribute_value.
    Now i_action and i_attribute_value can be directly linked through action_seq in i_action and ia_action_seq in i_attribute_value. A left join built between these two tables provides results for all actions (including actions which have no attributes) and attribute values (see query 1 below).
    There are two issues. First, I only want the first two attributes. In order to specify the first two attributes, I also have to link i_attribute_value to shared_action_attribute (which is where the order is stored). I can build a simple query (without the left join) linking the three tables but then actions with no attributes would be excluded from my result set (see query 2 below).
    The second issue is that I would actually like one row returned for each action with first_attribute and second_attribute as columns instead of two rows.
    The final query will be used to create a materialized view.
    Here are the tables and examples of what's stored in them:
    TABLE i_action
    Name Type
    ACTION_SEQ NUMBER(10)
    ACTION_DATE DATE
    ACTION_CODE VARCHAR2(3)
    DELETED VARCHAR2(1)
    EXAMPLE ROWS
    ACTION_SEQ ACTION_DATE ACTION_CODE DELETED
    45765668 09-OCT-09 B2 A
    45765670 09-OCT-09 BA A
    45765672 09-OCT-09 B6 A
    45765673 09-OCT-09 B4 A
    45765674 09-OCT-09 G1 A
    45765675 09-OCT-09 M3 A
    TABLE i_attribute_value
    Name Type
    IA_ACTION_SEQ NUMBER(10)
    SACTATT_SACT_CODE VARCHAR2(3)
    SACTATT_SAT_TYPE VARCHAR2(3)
    VALUE VARCHAR2(50)
    EXAMPLE ROWS
    IA_ACTION_SEQ SACTATT_SACT_CODE SACTATT_SAT_TYPE VALUE
    45765668 B2 ACO 37B
    45765670 BA ROA D
    45765670 BA ROR P
    45765672 B6 CAT C
    45765673 B4 RFC E
    45765673 B4 TRC P
    45765673 B4 RUN 7
    45765674 G1 SS 23567
    45765674 G1 ASG W
    TABLE shared_action_attribute
    Name Type
    SACT_CODE VARCHAR2(3)
    SAT_TYPE VARCHAR2(3)
    ORDER NUMBER(2)
    TITLE VARCHAR2(60)
    EXAMPLE ROWS
    SACT_CODE SAT_TYPE ORDER TITLE
    B2 ACO 1 Office code
    BA ROR 1 Reason for reopen
    BA ROA 2 Reopen authority
    B6 CAT 1 Category
    B4 RFC 1 Receiving function code
    B4 RUN 2 Receiving unit code
    B4 TRC 3 Transfer reason code
    G1 SS 1 Staff sequence
    G1 ASG 2 Assignment reason
    QUERY 1:
    This is my current query along with its results. Most of it is straightforward select but one column is populated using the last_value analytical function (thanks to you guys). The last column in the below view stores the attribute value. What I want is to replace that single column with two columns named first_attribute and second_attribute and to eliminate any other attributes.
    SELECT ia.action_seq, ia.action_date, ia.action_code cod,
    NVL
    (LAST_VALUE (CASE
    WHEN ia.action_code = 'G1'
    AND iav.sactatt_sat_type = 'SS'
    THEN VALUE
    WHEN ia.action_code IN ('A0', 'A1')
    THEN '67089'
    END IGNORE NULLS
    ) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
    ia.serial_number, ia.action_seq),
    '67089'
    ) staff_seq,
    value
    FROM i_action ia LEFT JOIN i_attribute_value iav
    ON iav.ia_action_seq = ia.action_seq
    WHERE ia.deleted = 'A';
    ACTION_SEQ ACTION_DA COD STAFF_SEQ VALUE
    45765668 09-OCT-09 B2 67089 37B
    45765670 09-OCT-09 BA 67089 D
    45765670 09-OCT-09 BA 67089 P
    45765672 09-OCT-09 B6 67089 C
    45765673 09-OCT-09 B4 67089 E
    45765673 09-OCT-09 B4 67089 P
    45765673 09-OCT-09 B4 67089 7
    45765674 09-OCT-09 G1 23567 23567
    45765674 09-OCT-09 G1 23567 W
    45765675 09-OCT-09 M3 23567
    QUERY 2:
    This query limits to the first two attributes but it also drops actions which have no attributes and it still creates multiple rows for each action instead of a single row with two columns for the attributes.
    SELECT ia.action_seq, ia.action_date, ia.action_code cod,
    NVL
    (LAST_VALUE (CASE
    WHEN ia.action_code = 'G1'
    AND iav.sactatt_sat_type = 'SS'
    THEN VALUE
    WHEN ia.action_code IN ('A0', 'A1')
    THEN '67089'
    END IGNORE NULLS
    ) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
    ia.serial_number, ia.action_seq),
    '67089'
    ) staff_seq,
    value
    FROM shared_action_attribute saa, ims_action ia, ims_attribute_value iav
    WHERE iav.ia_action_seq = ia.action_seq
    AND iav.sactatt_sact_code = saa.sact_code
    AND iav.sactatt_sat_type = saa.sat_type
    AND saa.display_order IN ('1','2')
    AND ia.deleted = 'A';
    ACTION_SEQ ACTION_DA COD VALUE
    45765668 09-OCT-09 B2 67089 37B
    45765670 09-OCT-09 BA 67089 D
    45765670 09-OCT-09 BA 67089 P
    45765672 09-OCT-09 B6 67089 C
    45765673 09-OCT-09 B4 67089 E
    45765673 09-OCT-09 B4 67089 7
    45765674 09-OCT-09 G1 23567 23567
    45765674 09-OCT-09 G1 23567 W
    I found this pretty complex to try to write out - I hope I've been clear.
    Thanks so much!

    Ok, here's more information with a simplified question. I figured out the syntax for building my query with the three tables. My final query returns multiple rows (multiple attributes per action). Instead of multiple rows, I'd like two columns (first_attribute, and second_attribute) in a single row (I only need the first two attributes).
    Here's the action table:
    CREATE TABLE I_ACTION
      ACTION_SEQ               NUMBER(10)           NOT NULL,
      ACTION_DATE              DATE,
      ACTION_CODE              VARCHAR2(3 BYTE)     NOT NULL,
      DELETED                  VARCHAR2(1 BYTE),
    );With the following rows added:
    Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
                  Values (45765668, '09-oct-2009', 'B2', 'A');
    Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
                  Values (45765670, '09-oct-2009', 'BA', 'A');
    Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
                  Values (45765672, '09-oct-2009', 'B6', 'A');
    Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
                  Values (45765673, '09-oct-2009', 'B4', 'A');
    Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
                  Values (45765674, '09-oct-2009', 'G1', 'A');
    Insert into I_ACTION (ACTION_SEQ, ACTION_DATE, ACTION_CODE, DELETED)
                  Values (45765675, '09-oct-2009', 'M3', 'A');
    COMMIT;The attribute table is:
    CREATE TABLE I_ATTRIBUTE_VALUE
      IA_ACTION_SEQ          NUMBER(10)             NOT NULL,
      SACTATT_SACT_CODE      VARCHAR2(3 BYTE)       NOT NULL,
      SACTATT_SAT_TYPE       VARCHAR2(3 BYTE)       NOT NULL,
      VALUE                  VARCHAR2(50 BYTE),
    );With the following rows:
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765668, 'B2', 'ACO', '37B');
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765670, 'BA', 'ROR', 'P');
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765670, 'BA', 'ROA', 'D');
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765672, 'B6', 'CAT', 'C');
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765673, 'B4', 'RFC', 'E');
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765673, 'B4', 'RUN', '7');
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765673, 'B4', 'TRC', 'P');
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765674, 'G1', 'SS', '23567');
    Insert into I_ATTRIBUTE_VALUE (IA_ACTION_SEQ, SACTATT_SACT_CODE, SACTATT_SAT_TYPE, VALUE)
                           Values (45765674, 'G1', 'ASG', 'W');
    COMMIT;And finally, the shared table:
    CREATE TABLE SHARED_ACTION_ATTRIBUTE
      SACT_CODE      VARCHAR2(3 BYTE)               NOT NULL,
      SAT_TYPE       VARCHAR2(3 BYTE)               NOT NULL,
      TITLE          VARCHAR2(25 BYTE)              NOT NULL,
      DISPLAY_ORDER  NUMBER(2)                      NOT NULL
    );With the following rows:
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('B4', 'RFC', 'Y', 'Rcv. Function Code', 1);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('B6', 'CAT', 'Y', 'Category', 1);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('G1', 'SS', 'Y', 'Staff Name', 1);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('B2', 'ACO', 'Y', '"Other" Office Code', 1);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('B4', 'RUN', 'Y', 'Receiving Unit Number', 2);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('B6', 'LEP', 'N', 'LEP Issue/Sub Category', 2);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('B4', 'TRC', 'Y', 'Transfer Reason Code', 3);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('B6', 'NEP', 'N', 'NEP Issue', 3);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('G1', 'ASG', 'Y', 'Assignment Reason', 2);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('B2', 'MSN', 'S', 'Machine Serial Number', 3);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('BA', 'ROR', 'Y', 'Reopen Reason', 1);
    Insert into SHARED_ACTION_ATTRIBUTE (SACT_CODE, SAT_TYPE, TITLE, DISPLAY_ORDER)
                                 Values ('BA', 'ROA', 'Y', 'Reopen Authority', 2);
    COMMIT;Now, this is my current query (it's changed from my first post):
    SELECT ia.action_seq, ia.ici_charge_inquiry_seq, ia.action_date,
           ia.serial_number, ia.reporting_office, ia.reporting_function,
           ia.reporting_unit, ia.action_code, ia.machine_serial_number,
           NVL
              (LAST_VALUE (CASE
                              WHEN ia.action_code = 'G1'
                                 THEN VALUE
                              WHEN ia.action_code IN ('A0', 'A1')
                                 THEN '67089'
                           END IGNORE NULLS
                          ) OVER (PARTITION BY ia.ici_charge_inquiry_seq ORDER BY ia.action_date,
                ia.serial_number, ia.action_seq),
               '67089'
              ) staff_seq,
           (CASE
              WHEN display_order = '1'
              THEN VALUE
           END) first_attribute,
           (CASE
              WHEN display_order = '2'
              THEN VALUE
           END) second_attribute
      FROM ims_action ia
      LEFT JOIN ims_attribute_value iav
           ON iav.ia_action_seq = ia.action_seq
      LEFT JOIN shared_action_attribute
           ON sactatt_sact_code = sact_code
         AND sactatt_sat_type = sat_type
    WHERE ia.deleted = 'A';Which gives me the following results:
    ACTION_SEQ ACTION_DA ACT STAFF_SEQ FIRST_ATTRIBUTE SECOND_ATTRIBUTE   
      45765668 09-OCT-09 B2  67089     37B                                
      45765670 09-OCT-09 BA  67089                     D                  
      45765670 09-OCT-09 BA  67089     P                                  
      45765672 09-OCT-09 B6  67089     C                                  
      45765673 09-OCT-09 B4  67089     E                                  
      45765673 09-OCT-09 B4  67089                     7                  
      45765673 09-OCT-09 B4  67089                                        
      45765674 09-OCT-09 G1  23567                     W                  
      45765674 09-OCT-09 G1  23567     23567                              
      45765675 09-OCT-09 M3  23567                                       The result I WANT is similar but I want the two separate attribute columns on one row as such:
    ACTION_SEQ ACTION_DA ACT STAFF_SEQ FIRST_ATTRIBUTE SECOND_ATTRIBUTE   
      45765668 09-OCT-09 B2  67089     37B                                
      45765670 09-OCT-09 BA  67089     P               D                  
      45765672 09-OCT-09 B6  67089     C                                  
      45765673 09-OCT-09 B4  67089     E               7                  
      45765674 09-OCT-09 G1  23567     23567           W                  
      45765675 09-OCT-09 M3  23567                          Thanks so much!

  • Help with sql - Left Join

    Hi,
    Below are the details of what I am attempting to do.
    DB version: 10.2.0.4.0
    Sample Table Definition
    create table t_cnf
    conf_id number,
    conf_value number,
    conf_cat_id number,
    actv_flg    char(1)
    create table t_int_act
    int_acc_id   number,
    frst_mrch_id number,
    create_date  date
    create table t_int_act_cast
    int_acc_id   number,
    cast_id      number
    create t_cast_alt_nmnt
    cas_alt_nmt_id number,
    cas_alt_id     number,
    cast_id        number,
    enrl_flg       char(1),
    src_id         number
    );Sample Data
    insert into t_cnf values (1, 78965098, 12, 'Y');
    insert into t_cnf values (1, 78965098, 13, 'Y');
    insert into t_int_act values (234,78965098, trunc(sysdate) - 1);
    insert into t_int_act_cast values (234, 560432);
    insert into t_cas_alt_nmnt values (1, 2, 560432, 'Y', 2); Need to fetch all cast_ids that are not in t_cast_alt_nmnt or cast_ids that are present in t_cast_alt_nmnt but have t_cast_alt_nmnt.enrl_flg = 'N' and t_cast_alt_nmnt.cast_alt_id in (2,3) and t_cast_alt_nmnt.src_id <> 2
    for t_int_act.frst_mrch_ids matching t_cnf.conf_vale
    Records fetch will insert a record into t_cast_alt_nmnt with css_alt_id 2 or 3 (determined by pe_or_pd).
    I attempted to write below sql. This works fine when cast_id does not exists in t_cast_alt_nmnt but will not return correct results when there is a record in t_cast_alt_nmnt matching above criteria.
    select
        iac.cast_id                            cast_id,
        sysdate                                upd_date,               
        case
            when c.conf_cat_id = 12 then 2
            when c.conf_cat_id = 13 then 3
        end
            pe_or_pd           
    from
        t_cnf                  c
    join    
        t_int_act          ia
    on
        ia.frst_mrch_id = c.conf_value
    join              
        t_int_act_cast iac
    on
        ia.int_acc_id = iac.int_acc_id
    left join       
        t_cast_alt_nmnt     can
    on
        can.cast_id = iac.cast_id     and
        can.enrl_flg = 'N'            and
        can.cas_alt_id in (2,3)       and
        can.src_id <> 2      
    where                 
        c.conf_cat_id              in (12,13)                           and
        c.actv_flg                 = 'Y'                                and
        -- Fetch all new customer created day before.   
        ia.create_date             >= trunc(sysdate) - 1                   
        Expected results
    With no cast_id record in t_cast_alt_nmnt
    cast_id upd_date pe_or_pd
    560432 4/19/2012 2
    560432 4/19/2012 3
    With cast_id record in t_css_alt_nmt (insert provided)
    cast_id upd_date pe_or_pd
    560432 4/19/2012 3
    Appreciate your help
    Edited by: user572194 on Apr 19, 2012 1:04 PM

    Thanks Frank for taking time to look into this and providing sql. I will test is against use cases (mentioned below).
    And I apologize for the typos. I had to change table and column names as it is policy of our company not to post data model details in public forums.
    Requirement:
    1. New cast ids will be added daily and these will get inserted into t_int_act and t_int_act_cas
    2. t_cnf has 2 conf_cat_id configured 12 and 13 and each conf_cat_id will have same conf_values (same as t_int_act.frst_mrch_id) but actv_flg might be different (set to N for 12 and Y for 13). Need to fetch only active ones
    3. t_cas_alt_nmnt will have cast_ids that are enrolled to receive certain mails if enrl_flg is Y for these. Not all cast_ids will have record in this table.
    When a cast_id is enrolled by customer service, a record will get inserted with src_id = 2.
    4. Requirement is to enroll new cast_ids created with frst_mrch_id matching t_cnf.conf_value where conf_cat_id in (12,13)
    Match criteira:
    If t_int_act_cas.cast_id exists in t_cas_alt_nmnt and have enrl_flg = 'Y' for cas_alt_id = 2 then
    insert record with same cast_id, enrl_flg = 'Y' and css_alt_id = 3
    If t_int_act_cas.cast_id exists in t_cas_alt_nmnt and have enrl_flg = 'Y' for cas_alt_id = 3 then
    insert record with same cast_id, enrl_flg = 'Y' and css_alt_id = 2
    If t_int_act_cas.cast_id exists in t_cas_alt_nmnt and have enrl_flg = 'N' for cas_alt_id in (2,3) and src_id = 2 then
    Ignore this record.
    if t_int_act_cas.cast_id not exists in t_cas_alt_nmnt then
    insert 1 record each with cast_id, enrl_flg = 'Y' for css_alt_id 2 and 3
    Hope above explanation makes sense.
    By the way I tried below sql. Yet to test it for all use cases but it worked for the last two.
    Note on PE_OR_PD column. I am just using this column to write separate inserts for css_alt_id 2 and 3.
    select
         cast_id,
         upd_date,
         pe_or_pd
    from    
         (select
                    iac.cast_id                        cast_id,
                    sysdate                            upd_date,
                    case
                        when c.conf_cat_id = 12 and can.cas_alt_id in (2,3) and enrl_flg = 'Y' then null
                        when c.conf_cat_id = 13 and can.cas_alt_id in (2,3) and enrl_flg = 'Y' then null
                        when c.conf_cat_id = 12 and nvl(can.cas_alt_id,2) = 2 and nvl(can.enrl_flg,'Y') = 'N' and can.src_id <> 2 then 'PE'
                        when c.conf_cat_id = 13 and nvl(can.cas_alt_id,3) = 3 and nvl(can.enrl_flg,'Y') = 'N' and can.src_id <> 2 then 'PD'       
                        when c.conf_cat_id = 12 and nvl(can.cas_alt_id,2) = 2 and nvl(can.enrl_flg,'Y') = 'Y' then 'PE'                                                                     
                        when c.conf_cat_id = 13 and nvl(can.cas_alt_id,3) = 3 and nvl(can.enrl_flg,'Y') = 'Y' then 'PD'                                                          
                    end
                        pe_or_pd              
                from
                    t_cnf              c,   
                    t_int_act          ia,      
                    t_intl_act_cus     iac,
                    t_cas_alt_nmnt     can              
                where
                    c.conf_value               = ia.frst_mrch_id               and
                    ia.internal_account_id     = iac.int_act_id                and 
                    can.cast_id(+)             = iac.cast_id                   and                               
                    c.conf_cat_id              in (12,13)                      and
                    c.actv_flg                 = 'Y'                           and
                    -- Fetch all new customer created after last run.   
                    ia.create_date             >= trunc(sysdate) - 1                                                                     
         ) enrl_cust
    where
        pe_or_pd is not null               
                    ;

Maybe you are looking for

  • How do i save file from laptop to my iphone

    how do i save file from laptop to my iphone

  • Find and delete duplicate files on my macbook pro?

    How can I find and delete duplicate files on my macbook pro. Just that i have so many and i think it is wasting a lot of memory etc on my mac! is there a simple and easy way to do so. Like i know in itunes you can just go to one of the opitions and s

  • Edge animate and dreamweaver

    I'm using the latest CC versions of these programs on a new Windows PC. I have created an animate_package .oam file and a web .html file and have included all supporting links and folders mirrored on our server. I can get the .oam working locally on

  • Can I produce such a result with a single query?

    I am having a table with records like A....B 1....20 2....19 3....03 4....09 5....74 6....24 7....31 Column A is a primary key and Column B has radomly generated positive integer numbers. I need to generate one more column C with randomly generated p

  • Left shift key is making a capital R..........

    My Right shift key tRies to adjust volume but still woRks....left shift key makes a capital R and when I just tRy to type the letteR R it is capitalized.....what is wRong with my macbook? you can email me at [email protected]