Query Help (Left Join?)

Hi all
Im trying to write a query and am having problems with the way that the data is displayed.
My issue is essentially with one column EMPL_STAT_CD.
Within this column contains diffrent words standing for diffrent things such as Table, Lamp etc.
With my query i am specifically looking for everyone that has bought a Table or a table AND lamp.
How i want the data to be displayed is
table Blank
table Blank
Table Blank
Table Lamp
Table Blank
Table Lamp
Im pretty sure i can do a left outer join to display all the data in the left table, but am having problems with displaying the right table with the blanks.
Current Query
SELECT
DISTINCT(A.PRSN_INTN_ID),
B.FRST_NM AS FIRST_NAME,
B.MID_NM AS MIDDLE_NAME,
B.LAST_NM AS LASTNAME,
B.BRTH_DT AS BIRTH_DATE,
A.EMPL_CAT_ID AS EMPLOYMENT_ID,
A.EE_EMPLCAT_EFBEGDT AS BEGIN_DATE,
C.ADDR_LINE_1_TX AS ADDRESS,
C.CITY_NM AS CITY,
C.ST_CD AS PROVINCE,
C.ZIP_CD AS POSTAL_CODE,
C.CTRY_CD AS COUNTRY_CODE,
B.PRIM_LANG_CD AS LANGUAGE,
D.DLVR_GRSS_AT AS PENSION_AMOUNT,
FROM
PRSN B,
PRSN_ADDR C,
PRSN_TXDS_DLVR D,
PRSN_DBPMTINST E,
EE_EMPL_CAT A
WHERE A.PRSN_INTN_ID = B.PRSN_INTN_ID AND
A.PRSN_INTN_ID = C.PRSN_INTN_ID AND
A.PRSN_INTN_ID = D.PRSN_INTN_ID AND
A.PRSN_INTN_ID = E.PRSN_INTN_ID AND
D.PMT_ID = E.PMT_ID AND
D.PMT_EFDT = '2008-03-01'
AND E.DB_PMTINST_STAT_CD = 'A'
AND E.PMT_INST_EFENDDT = '2299-12-31'
AND E.PMT_ADJ_CD NOT IN ('R', 'A')
AND E.PMT_ID IN(1000,6000,2510,2520)
AND B.CURR_RSLT_CD = 'Y'
AND A.EMPL_CAT_ID IN(Table,Lamp)
AND A.EE_EMPLCAT_EFENDDT='2299-12-31'
AND C.ADDR_ID = 10
AND C.PRSN_ADDR_EFENDDT = '2299-12-31'
AND C.CURR_RSLT_CD = 'Y'
Any input greatly appreciated

You don't have a query problem you have a design problem that goes back to database basics.
Never, ever, store multiple values in a single column.
Fix your design and the problem goes away.
http://www.psoug.org/reference/normalization.html

Similar Messages

  • Sub query in left join

    hi,
    I wanted 2 do some thing like this..
    Select A.C1, A.C2
    From A
    LEFT JOIN B
    ON A.C1 = B.C1 AND B.C2 = (SELECT T.C1 FROM T WHERE B.C2 = T.C1);How can i do dis?
    It is giving me exception :: ORA-01799: a column may not be outer-joined to a subquery
    but
    Select A.C1, A.C2
    From A
    LEFT JOIN B
    ON A.C1 = B.C1 AND B.C2 = 5;is working fine

    Hi,
    Atishay wrote:
    hi,
    I wanted 2 do some thing like this..
    Select A.C1, A.C2
    From A
    LEFT JOIN B
    ON A.C1 = B.C1 AND B.C2 = (SELECT T.C1 FROM T WHERE B.C2 = T.C1);
    Use curly brackets on the \  tags before anbd after formatted text on this site.
    How can i do dis?
    It is giving me exception :: ORA-01799: a column may not be outer-joined to a subquery
    but
    Select A.C1, A.C2
    From A
    LEFT JOIN B
    ON A.C1 = B.C1 AND B.C2 = 5;is working fineHere's one way:Select      A.C1, A.C2
    From           A
    LEFT JOIN      B
                   ON      A.C1 = B.C1
                   AND      B.C2 IN (
                                  SELECT      C1
                                  FROM      T
    Another way is to join b and t before outer-joining to a.
    I hope this answers your question.
    If not, post a little sample data CREATE TABLE and INSERT statements for all tables) and the results you want from that data.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

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

  • Left joins on multi-million rows

    i have a simple query doing left joining on several tables, upward of 7 tables. each table has several hundred million rows.
    tblA is 1:M tblB and tblB is 1:M tblC and so on.
    how to tune a query liked that?
    sample query is
    select distinct
    a.col,b.col,c.col
    from tblA a left join tblB b
    on a.id=b.id
    and a.col is not null
    left join tblC
    on b.id=c.id
    and c.col > criteria
    thanks.

    hi
    a simple query is liked
    SELECT my_DEP.description,
    my_DEP.addr_id,
    hundredRowsTbl.address,
    5MillTbl.checkin_TIME,
    5MillTbl.checkout_TIME,
    hundredRowsTbl.ID2,
    5MillTbl.ID,
    5MillTbl.col2,
    my_DEP.col3,
    5MillTbl.col13,
    hundreds.desc,
    50mmTbl.col6,
    50mmTbl.col5,
    5MillTbl.col33
    FROM
    my.5MillTbl 5MillTbl
    LEFT OUTER JOIN
    my.50mmTbl 50mmTbl
    ON 5MillTbl.ID = 50mmTbl.ID
    LEFT OUTER JOIN my.hundreds hundreds
    ON 5MillTbl.banding =
    hundreds.banding
    INNER JOIN my.my_DEP my_DEP
    ON 5MillTbl.organization_ID = my_DEP.organization_ID
    INNER JOIN my.my_40millTbl
    ON 5MillTbl.seqID = my_40millTbl.seqID
    LEFT OUTER JOIN my.hundredRowsTbl hundredRowsTbl
    ON my_DEP.addr_id = hundredRowsTbl.ID2
    LEFT OUTER JOIN my.30millTbl 30millTbl
    ON my_DEP.organization_ID = 30millTbl.dept_id
    WHERE 1=1
    AND 5MillTbl.ID IS NOT NULL
    AND ( 5MillTbl.checkout_TIME >= TO_DATE ('01-01-2009 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
    AND 5MillTbl.checkout_TIME <TO_DATE ('12-31-2010 00:00:00', 'DD-MM-YYYY HH24:MI:SS')
    AND ( 5MillTbl.col2 IS NULL
    OR NOT (5MillTbl.col2 = 5
    OR 5MillTbl.col2 = 6)
    AND 5MillTbl.ID IS NOT NULL
    AND 30millTbl.TYPE= '30'
    AND my_DEP.addr_id = 61

  • Left Join query help

    select * from ort
    bid mid
    18083 7
    select * from st
    tid bid mid act
    318 18083 5 20091
    318 18083 6 20091
    321 18083 7 NULL
    318 18083 16 23970
    my out put should be
    318 18083 6 20091
    (basic idea is
    In order to do this I wrote the following query. But I am getting the following error ora-01799. How do i fix this?
    select ort.bid,st.tid from ort
    left join st
    on ort.BiD = st.bid
    and st.mid in
    (select max(MID)
    from St
    where BID = ort.BID and TID is not null and MID <= ort.MID
    and ACT is not null
    )

    May be this will clear up what I am trying to acheive a little better. I truly appreciate all your help. I have enclosed column headings and data items within double quotes and data is enclosd in double-quotes and separated by comma.
    SQL> desc ort
    "Name" "Null?" "Type"
    "BID" "NUMBER"
    "MID" "NUMBER"
    SQL> desc st
    "Name" "Null?" "Type"
    "TID" "NUMBER"
    "BID" "NUMBER"
    "MID" "NUMBER"
    "ACT" "NUMBER"
    "LTP" "NUMBER(10)"
    SQL> select * from ort
    2 ;
    "BID" "MID"
    "18083", "7"
    "18083", "6"
    "18083", "16"
    "18083", "277"
    "18083", "117"
    SQL> select * from st;
    "TID" "BID" "MID" "ACT" "LTP"
    "NULL", "18083", "117", "NULL", "246"
    "NULL", "18083", "277", "NULL", "246"
    "246", "18083", "272", "54998", "246"
    "318", "18083", "6", "20091" "NULL"
    "321", "18083", "7", "NULL", "NULL"
    "318", "18083", "16", "23970", "NULL"
    6 rows selected.
    SQL> SELECT ort.bid, st.tid, st.mid, st.act
    2 FROM ort
    3 LEFT OUTER JOIN
    4 st
    5 ON ort.bid = st.bid
    6 AND st.mid IN (SELECT mid
    7 FROM myortview);
    "BID" "TID" "MID" "ACT"
    "18083", "246", "272", "54998"
    "18083", "246", "272", "54998"
    "18083", "246", "272", "54998"
    "18083", "246", "272", "54998"
    "18083", "246", "272", "54998"
    SQL> -- expected result is
    bid tpid ort.mid st. mid
    "18083", "246", "277", "272"
    "18083", "246", "117", "116"
    "18083", "318", "16", "16"
    "18083", "318", "6", "6"
    "18083", "318", "7", "6"

  • Left Join query: revisited... I have to explain at user meeting tomm. pls..

    Hi Everyone,
    Can someone pls shed some light on the situation below
    I am understanding alot of what Michael and Rod wrote.... with my prev. post of LEFT JOIN and testing for
    not null and doing a double Boolean OR etc.
    - but- AM NOT understanding why the IS NOT NULL works, without the double boolean OR
    Pls help... have to explain what left join means to user tomm. I'm going to demo the query below and
    not the one with the double boolean OR bec. maybe too much info to present at one sitting. tx, sandra
    =====================
    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

    Hi,
    OK, I will try to explain this. When you outer join table B to table A then the rows in table A which do not match any rows in table B will returned with NULL in the columns from the table B.
    Oracle uses the syntax ( +) for outer joins. Now if you add another condition using the ( +) syntax (as shown below) the condition will be processed before the table is joined. Therefore if table A does not match any rows in table B which have col2=1 then the row from table A will be returned with NULLs for the table B columns.
    SELECT A.col1, B.col1
    FROM A, B
    WHERE A.col1 = B.col1( +)
    AND B.col2( +)=1
    Now, if the condition B.col2=1 was used instead then the condition would be processed after the join and therefore the rows from table A that were joined to table B but did not meet the condition would not be returned by the query.
    This applies to a WHERE clause and to the HAVING clause, but with one exception. If you use the ( +) within a group function in a HAVING clause then the ( +) will have no affect because the condition must be processed after group by and group by can only be processed after the join. Therefore MAX(B.col2( +)) = 1 is processed after the join even through it uses the ( +) syntax.
    You cannot use an OR or an IN with the ( +) syntax because the meaning of the OR in this situation is ambiguous, is the OR done before or after the join. A query with an OR or IN in an outer will fail with an Oracle ORA-01719 error. Discoverer recognises this situation and removes the ( +) so that the error does not occur. However, without the ( +) the conditions are processed after the join.
    Using the ( +) with IS NULL, e.g. col2( +) IS NOT NULL works in the same way. You just have to remember that the col2( +) could be NULL as a result of the outer join and therefore if the condition is processed after the query then the IS NOT NULL will remove the outer joined rows.
    Hope that is clear.
    Rod West

  • Help in Joining query

    Hi, How I can get desired result. I am joining two tables but if date timeline does't exist in #two table then should show hyphen (-). Please help on this query. Thanks.
    create table #one (code_p char(4), code_h char(2), code_date datetime)
    insert into #one values ('DEHG','2','2010-01-01')
    insert into #one values ('DEHG','2','2011-01-01')
    insert into #one values ('DEHC','2','2009-01-01')
    insert into #one values ('DEHG','2','2012-01-01')
    create table #two (code_p char(4), code_h char(2), code_date datetime)
    insert into #two values ('DEHG','2','2010-01-01')
    insert into #two values ('DEHC','2','2009-01-01')
    select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
    p.code_p code_p_two, p.code_h code_h_two, p.code_date code_date_two from #one p join #two a on p.code_p = a.code_p
    --Result from the above query
    code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
    DEHG     2    2010-01-01     DEHG     2     2010-01-01
    DEHG     2    2011-01-01     DEHG     2     2010-01-01
    DEHC     2    2009-01-01     DEHG     2     2009-01-01
    DEHC     2    2012-01-01     DEHG     2     2009-01-01
    --Desired result
    code_p_one code_h_one code_date_one code_p_two code_h_two code_date_two
    DEHG     2    2010-01-01     DEHG     2     2010-01-01
    DEHG     2    2011-01-01     DEHG     2     -
    DEHC     2    2009-01-01     DEHG     2     2009-01-01
    DEHC     2    2012-01-01     DEHG     2     -

    Try this:
    select p.code_p code_p_one, p.code_h code_h_one, p.code_date code_date_one,
    p.code_p code_p_two, p.code_h code_h_two, ISNULL(CONVERT(varchar(50),a.code_date,121),'-') code_date_two
    from #one p
    left join #two a on p.code_p = a.code_p and p.code_date=a.code_date
    If this post answers your query, please click "Mark As Answer" or "Vote as Helpful".

  • Left join query prob

    Hi,
    I have one ejbql for selecting records from one table which are not in the other table.There is actually records in the data base but by using this query it is retrieving noting . The corresponding pl/sql query is working fine and it is retrieve correct result .what is wrong with my query.. Plz help me to correct this query...
    My ejbql is below...
    EJB-QL
    SELECT C.name FROM person C LEFT JOIN C.address FC WHERE C.id.name= FC.id.name AND FC.id.pcode IS NULL
    There is no result while executing this query. The correspoinding pl sql query is
    PL/SQL
    SELECT e_person .* FROM e_person ep LEFT JOIN e_address ea ON ep .name= ea .name WHERE ea.pcode IS NULL
    plz help ...
    Thanks in advance
    Ani

    Enable logging and include the SQL generated for the JPQL.
    JPQL will also join via the primary/foreign key define in the mapping when you do C.address, if this is not name then you may be joining by something else. You could just declare the Address independent of the Employee if you do not wish to join by primary key (although this seems odd).
    -- James : http://www.eclipselink.org

  • 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

  • How to generate a query involving multiple tables(one left join others)

    Hi, all,
    I want to query a db like these:
    I need all the demographics information(from table demo) and their acr info(from table acr), and their clinical info(from table clinical), and their lab info(from table lab).
    The db is like this:
    demo->acr: one to many
    demo->clinical info: one to many
    demo->lab info: one to many
    I want to get one query result which are demo left join acr, and demo left join clinical, and demo left join lab. I hope the result is a record including demo info, acr info, clinical info, and lab info.
    How could I do this in SQL?
    Thanks a lot!
    Qian

    Thank you very, very much!
    Actually, I need a huge query to include all the tables in our db.
    We are running a clinical db which collects the patients demographics info, clinical info, lab info, and many other information.
    The Demographics table is a center hub which connects other tables. This is the main architecture.
    My boss needed a huge query to include all the information, so others could find what they need by filtering.
    As you have found, because one patients usually has multiple clinical/lab info sets, so the result will be multiplied! the number of result=n*m*k*...
    My first plan is to set time point criteria to narrow all the records with one study year. If somebody needs to compare them, then I have to show them all.
    So I have to know the SQL to generate a huge query including as many tables as possible.
    I show some details here:
    CREATE TABLE "IMMUNODATA"."DEMOGRAPHICS" (
    "SUBJECTID" INTEGER NOT NULL,
    "WORKID" INTEGER,
    "OMRFHISTORYNUMBER" INTEGER,
    "OTHERID" INTEGER,
    "BARCODE" INTEGER,
    "GENDER" VARCHAR2(1),
    "DOB" DATE,
    "RACEAI" INTEGER,
    "RACECAUCASIAN" INTEGER,
    "RACEAA" INTEGER,
    "RACEASIAN" INTEGER,
    "RACEPAC" INTEGER,
    "RACEHIS" INTEGER,
    "RACEOTHER" VARCHAR2(50),
    "SSN" VARCHAR2(11),
    PRIMARY KEY("SUBJECTID") VALIDATE
    CREATE TABLE "IMMUNODATA"."ACR" (
    "ID" INTEGER NOT NULL,
    "THEDATE" DATE ,
    "SUBJECTID" INTEGER NOT NULL,
    "ACR_PAGENOTCOMPLETED" VARCHAR2(1000) ,
    "ACR_MALARRASHTODAY" INTEGER ,
    "ACR_MALARRASHEVER" INTEGER ,
    "ACR_MALARRSHEARLIESTDATE" DATE ,
    PRIMARY KEY("ID") VALIDATE,
    FOREIGN KEY("SUBJECTID") REFERENCES "IMMUNODATA"."DEMOGRAPHICS" ("SUBJECTID") VALIDATE
    CREATE TABLE "IMMUNODATA"."CLIN" (
    "ID" INTEGER NOT NULL,
    "THEDATE" DATE ,
    "SUBJECTID" INTEGER NOT NULL,
    "CLIN_PAGENOTCOMPLETED" VARCHAR2(1000) ,
    "CLIN_FATIGUE" VARCHAR2(20) ,
    "CLIN_FATIGUEDATE" DATE ,
    "CLIN_FEVER" VARCHAR2(20) ,
    "CLIN_FEVERDATE" DATE ,
    "CLIN_WEIGHTLOSS" VARCHAR2(20) ,
    "CLIN_WEIGHTLOSSDATE" DATE ,
    "CLIN_CARDIOMEGALY" VARCHAR2(20) ,
    PRIMARY KEY("ID") VALIDATE,
    FOREIGN KEY("SUBJECTID") REFERENCES "IMMUNODATA"."DEMOGRAPHICS" ("SUBJECTID") VALIDATE
    Other tables are alike.
    Thank very much!
    Qian

  • Don'T repeat item with a LEFT JOIN QUERY

    Hello,
    I would like to know how display the following results:
    *Name*:  John Fox
    *Sales:*  1- LAPTOP
                    2- HARDDRIVE
                    3- COMPUTERHere is my 2 tables: CUSTOMER and SALES
    CUSTOMER
    ID NAME GENDER
    1 John Mayer F
    2 Melissa John F
    3 Julie Black F
    4 Mickael Fox M
    5 John Fox M
    SALES
    ID ID_CUSTOMER TYPE
    1 1 Boat
    2 1 TV
    3 4 CD PLAYER
    4 5 LAPTOP
    5 5 HARDDRIVE
    6 5 COMPUTER
    My QUERY
    SELECT customer.Name as NAME, customer.Gender, sales.TYPE
    from customer
    LEFT JOIN sales
    ON customer.ID = sales.ID_CUSTOMER
    WHERE customer.Name = 'John Fox'The problem: If I use the default template, I have:
    NAME GENDER TYPE
    John Fox M LAPTOP
    John Fox M HARDDRIVE
    John Fox M COMPUTER I don'T want the Name John Fox to be repeated at each row.
    I tried to add: #Name# in the REGION DEFINITION - REGION HEADER but I have this result:
    #NAME#
    NAME GENDER TYPE
    John Fox M LAPTOP
    John Fox M HARDDRIVE
    John Fox M COMPUTER
    So, what can I do to have this result? Change the query???
    Name:  John Fox
    Sales: 1- LAPTOP
           2- HARDDRIVE
            3- COMPUTER               thanks,
         Roseline

    Hi Roseline,
    You can adapt the solution suggested in this post Re: More than 1 records in one cell
    Thanks,
    Manish

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

  • JPA OnetoMany  QUERY LEFT JOIN BUG

    Using JPA in JDev 10.1.3.1.0.3984
    Database: Firebird 1.51LI-V1.5.3.4870 Firebird 1.5/tcp
    Driver: Jaybird JCA/JDBC driver Version: 2.1
    TopLink, version: Oracle TopLink Essentials - 2006.8 (Build 060829)
    If I use normal JOIN it works.
    On LEFT JOIN I get a {oj [/b] before the table name and a [b]} at the end.
    public class Cliente{
        @OneToMany(mappedBy = "cliente")
        @JoinColumn(name = "CDCLIENTE", referencedColumnName = "CDCLIENTEREQUISITANTE")
        private List<Requisicao> requisicoes;
    public class Requisicao
        @ManyToOne
        @JoinColumn(name = "CDCLIENTEREQUISITANTE", referencedColumnName = "CDCLIENTE")
        private Cliente cliente;
    EntityManager em = getEntityManager();
    String sql = "SELECT c FROM Cliente c LEFT JOIN c.requisicoes req";
    Query q = em.createQuery(sql);
    List rs = q.getResultList();Result SQL:
    SELECT DISTINCT t0. <OMITTED> FROM {oj [/b]CLIENTE t0 LEFT OUTER JOIN REQUISICAO t1 ON (t1.CDCLIENTEREQUISITANTE = t0.CDCLIENTE)[b]}

    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

  • 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

  • Serious trouble with new iPod - maybe you can help?

    Please help if you can. 15 hours into troubleshooting this and I am desperate!!! I just purchased a new 5th-gen, 60GB ipod. I already have a 1st gen, 10GB iPod. My old iPod is presently working great with no problems. The new iPod, however, is not be

  • Need some help understanding VPNs on Windows 8.1

    I set up an incoming VPN connection on a home PC - myVPNserver - running Win 8.1 Pro (by going to Network Connections/ALT File/New Incoming Connection).  I enabled Port Forwarding on my NetGear Router to forward port 1723 to the internal IP Address o

  • Problem booting Power Mac G4 DA

    Hello, Have a G4 PowerMac (DigitalAudio) and can't get it to boot. Here are the specs: G4,1.5Ghz,1GB RAM, MacOS 10.5.4, Superdrive, 6 HD's - 150GB(main),2 IDE 500GB+1 150BG on IDE card,2 SATA 160GB in IDE card, USB&Firewire expansion cards & ATI vide

  • Stuck Pixels on iPod Touch

    My iPod Touch is having the stuck pixel lcd problem. I have about 3 significantly bright stuck pixels and a whole bunch of not so bright ones. I don't seem to have the inverted black problem though. Is this an issue that can be easily fixed by an upd

  • FYI_What Black Magic Multibridge does to Prem on a MAC

    I mentioned last year while chasing up a few issues that I would rebuild my system from scratch to test out what Black Magic Multibridge Pro 2 does or doesn't do with Premiere in an effort to work out what was causing my problems. I have a Mac Pro 4.