Left join problem

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

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

Similar Messages

  • 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 >= '29-DEC-2008' and dmDate.CalendarDate < '
    Then fctinsertchargedetail.Amount_insertDetail Else 0 End)) As CurRev,
    (sum(Case When dmDate.CalendarDate >= '29-DEC-2007' and dmDate.CalendarDate < '
    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 >= '29-DEC-2007' And dmDate.CalendarDate < ') 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

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

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

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

  • How To do a LEFT JOIN in Oracle 8i

    Hello
    To explain my problem in a simple way: I have two tables, PROVA1 and PROVA2. Both have a primary key with two fields (CHIAVE1 amd CHIAVE2, numbers).
    I have to search for all records in A but not in B. In Oracle 8 LEFT JOIN is not available and I do not Know how doing it.
    I have read something about + operator, but I am not sure. What about:
    Select * from PROVA1 P1, PROVA2 P2 where
    (P1.CHIAVE1(+) = P2.CHIAVE1) and
    (P1.CHIAVE2(+) = P2.CHIAVE2) and
    (P2.CHIAVE1 IS NULL) and
    (P2.CHIAVE2 IS NULL)
    Thank you
    Garetano Recchi

    Gaetano, you're really close.
    The (+) sign goes near to the table where the records can be missed. In your example near P2 columns.
    Select *
      from PROVA1  P1,  PROVA2  P2
      where P1.CHIAVE1 = P2.CHIAVE1(+)
      and P1.CHIAVE2 = P2.CHIAVE2(+)
      and P2.CHIAVE1 IS NULL
      and P2.CHIAVE2 IS NULLYou can anyway use the minus operator
    Select *
      from PROVA1
      where (chiave1,chiave2) in (select chiave1, chiave2 from prova1 minus select chiave1, chiave2 from prova2);If you want to download a free book (in italiano) for oracle beginners go to
    My Oracle-related blog
    Max

  • Outer join problem (ORA-01799)

    We have a database design roughly as follows:
    - A STAFF table (columns don't matter here).
    - Resources have a cost per hour that varies over time, so we have a STAFF_COST table with an effective date and a cost per hour
    - A PROJECT table (columns don't matter here).
    - Projects can have staff assigned, so we have a PROJECT_STAFF table which has foreign keys to the PROJECT and STAFF table.
    - Project staff have a cost per hour, which can vary over time, and be different to the (default) staff costs. So we have a PROJECT_STAFF_COST table which uses the PROJECT_STAFF foreign key, with an effective date and a cost per hour
    - Staff work on tasks so we have a TIMESHEET_TASK and TIMESHEET_DAY tables which define a project worked on, task within the project (optional as time can be 'entered against the project', who is recording the time, the hours worked and the day the hours were worked.
    So when timesheet information is entered we have three scenario's that we need to cover.
    1) The resource is a member of the project and the hours were worked on a day for which we have a project staff cost. That is, the project staff cost table has one or more rows for the staff member assigned to the given project with an effective date before the date the hours were entered against.
    2) The resource is a member of the project but the hours were worked on a day for which we do not have a project staff cost. That is, the project staff cost table has one or more entries for the staff member assigned to the given project, but all the effective dates are after the date the hours were entered against.
    3) The resource is not a member of the project. That is, the project staff cost table does not have any rows for the staff member. Time was entered 'against the project'.
    We need to work out the actual cost of the project. So we need to retrieve every day's timesheet entry, returning the hours assigned and the cost per hour relevant for that day. I have the following query:
    select tsh.staff_id, s.full_name, tsd.entry_date, tsd.hours as ProjectHours,
    psCOST_INFO.cost_per_hour as ProjectCost
    from timesheet_day tsd
    inner join timesheet_task tst on tst.timesheet_task_id = tsd.timesheet_task_id
    inner join timesheet_header tsh on tst.timesheet_header_id = tsh.timesheet_header_id
    inner join staff s on s.staff_id = tsh.staff_id
    left join (Select ps.project_id, ps.staff_id, psc.project_staff_id, psc.effective_date, psc.cost_per_hour
    from project_staff ps
    inner join project_staff_cost psc on ps.project_staff_id = psc.project_staff_id) as psCOST_INFO
    on psCOST_INFO.staff_id = tsh.staff_id and psCOST_INFO.project_id = tst.project_id
    and psCOST_INFO.effective_date = (select max(ps2.effective_date) from project_staff_cost ps2
    where ps2.project_staff_id = psCOST_INFO.project_staff_id
    and ps2.effective_date <= tsd.entry_date)
    where tst.project_id = 55825
    Using the left join covers scenario's 2 and 3 above because I will get null in the cost columns and can then take appropriate action. If I were to use an inner join, then hours in timesheets from scenario's 2 and 3 would be excluded, which is not what we want.
    The subselect using the MAX aggregate function is required to get the cost per hour most relevant for the timesheet day. That is, if there are several effective dates for the project staff member before the date in question, we want the most recent one. We can't just use the MAX one, however in case there is an effective date after the particular timesheet date. Sheesh...
    This query works fine in SQL Server. It it not allowed in Oracle and returns an ORA-01799 column may not be outer joined to a subquery.
    I'm not going to bother to ask why not. I just need a way to do what I want. I've spent days trying to move the code around but I either end up with an inner join (which returns fewer rows than I want) or it just plain don't work.
    Can someone help me rework this query to achieve the result I want?
    Thanks, Andrew

    Thanks for your reply, Laurent. In my experience trying to cut important corners in explaining a problem only serves to make it more difficult to solve. That pretty much was the smallest reproducable query that demonstrates the complexity of the problem I have. I'm not just trying to get which publishers live in the 'CA' state here...
    From what I have just read about rank() it serves the same purpose as max() on a given column, and getting the maximum or top ranked one just doesn't cut it. As I said in my original post that provided all the relevant (and no spurious) information on the problem, it is possible that there are effective dates AFTER the date we are interested in and they have to be excluded.
    I have to get the project staff cost row with the latest date that is before the timesheet date. That means I have to reference data in the outer query. Oracle seems to have a problem with that when used in an outer join.
    We are currently going down the track of 3 UNION'd statement to cover the 3 scenario's. A single query would be more efficient so if anyone can provide guidance I would appreciate it.
    Thanks, Andrew

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

  • 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

  • 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

  • SQL Query join problem

    Hi,
    I have two tables in my db, the patient table holds details of patients, the contact table holds details of contacts related to the patient.
    patient table
    patientid - primary key - int
    patient name - varchar
    contact table
    contactid - primary key - int
    patientid - foreign key from patient table - int
    incontact - foreign key from paient table to relate contacts - int
    My contact table has the following data:
    contactid patientid incontact
    2              19           21
    2               19          22
    I can retrieve data for the patients that have been in contact with patientid 19, by using the following join:
    SELECT * FROM PATIENT
    LEFT JOIN incontact
    ON incontact.incontact = patient.patientid
    WHERE incontact.patientid = 19
    However, can you please tell me how I can get data from the patients table where the incontact is 21?
    So I can get contacts from patients and patients from contacts?
    Thankyou

    Thanks very much for your replies again.
    Basically, I have a table of patients, and I would like to link them to each other, many to many.
    I populate the incontact table, which stores the original posted patientID, and the new generated patientID. I populate the DB with the code below.
    <cfquery name="update" datasource="staffdirectory">
    SET NOCOUNT ON
    INSERT INTO patient (title,firstname,surname,gender,DOB,telephone,address1,address2,address3,town,postcode
    VALUES ('#title#','#firstname#','#surname#','#gender#',#createodbcdate(createdate(startyear, startmonth, startday))#    ,'#telephone#','#address1#','#address2#','#address3#','#town#','#postcode#
    SELECT @@Identity AS newid   
    SET NOCOUNT OFF
    </cfquery>
          <cfquery name="insert" datasource="staffdirectory">
      INSERT INTO incontact (related,incontact)
    VALUES (#patientid#,#update.newid#)
    </cfquery>
    This works fine and I can get all related patients by usingthe following query:
    SELECT * FROM patient
    LEFT JOIN incontact
    ON patient.patientid  = incontact.related
    WHERE  incontact.incontact = #patientid#
    MY problem occurs when I want to find related patients from the related column, the reverse relationship. I use this seperate query:
    SELECT * FROM patient
    LEFT JOIN incontact
    ON patient.patientid  = incontact.incontact
    WHERE  incontact.related= #patientid#
    Is there a way I can combine both queries, or is there a better way I can achieve the same result?
    Many thanks again

  • 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

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

  • SQL JOIN problem

    Hello,
    To output data on my .php website I use a SQL database. One
    particular page needs information from 3 tables:
    1. Product (product.id, product.name)
    2. Partner (partner.productid, parner.shopname)
    3. Shop (shop.shopshopname)
    I currently have this code running to make it happend:
    SELECT *
    FROM (product LEFT JOIN partner ON product.id =
    partner.productid) LEFT JOIN shop ON partner.shopnaam =
    shop.shopshopnaam
    WHERE product.categorie = 'Kinderwagens' AND
    product.hoofdmodel = '1'
    ORDER BY product.name ASC, shop.shopcpc DESC
    The idea is that every product.name gets outputted in a list
    just once and that it picks partner.productid of the row with the
    highest corresponding shop.cpc.
    Example: I have a lot of product.id's where product.id =
    "1000 is found 4 times in partner.productid. All product.name's are
    outputted and ascend correctly. However, product.name with
    product.id=1000 is outputted 4 times. I only want it outputted once
    where it pickes the corresponding partner.id where its
    corresponding shop.shopcpc is highest. What do I do to prevent it
    from outputting all 4?
    I know its kind of complex to explain, if there are questions
    please let me know.

    I kind of fixed this problem with a group by:
    SELECT *
    FROM (product LEFT JOIN partner ON product.id =
    partner.productid) LEFT JOIN shop ON partner.shopnaam =
    shop.shopshopnaam
    WHERE product.categorie = 'Kinderwagens' AND
    product.hoofdmodel = '1'
    GROUP BY product.naam
    ORDER BY product.naam ASC, shop.shopcpc DESC
    However, by doing this my ORDER BY shop.shopcpc doesnt work
    anymore. Anyone know how to fix this?

  • JPA and LEFT JOIN

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

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

  • Left Join in a View

    I'm using a left join in a view object but I get ORA-00942 Table or View does not exist.
    When I run the SQL Query in SQLDeveloper, it works fine. But when I use it in my ViewObject, I get the error. The Query looks like this (It is more difficult than this, but this is the part that I get the error in)
    SELECT LocationHistory.LOCATION_HISTORY_ID,
    LocationHistory.CONFIG_ITEM_ID,
    LocationHistory.EMPLOYEE_ID,
    LocationHistory.STD_LOCATION_ID,
    LocationHistory.FROM_DATE,
    LocationHistory.DESCRIPTION,
    StandardLocation.STANDARD_LOCATION_ID AS STANDARD_LOCATION_ID1,
    StandardLocation.NAME,
    StandardLocation.DESCRIPTION AS DESCRIPTION1
    FROM HSR_LOC_HISTORY LocationHistory
    LEFT JOIN HSR_STD_LOCATION StandardLocation
    ON LocationHistory.STD_LOCATION_ID = StandardLocation.STANDARD_LOCATION_ID
    WHERE STD_LOCATION_ID = 20
    Does anyone know what the problem could be? Thanks for the help in advance

    Hi,
    It looks like the VO validation thinks LEFT is a table (table or view does not exist)
    try
    FROM HSR_LOC_HISTORY LocationHistory,
    HSR_STD_LOCATION StandardLocation
    WHERE  LocationHistory.STD_LOCATION_ID = StandardLocation.STANDARD_LOCATION_ID(+)
    AND STD_LOCATION_ID = 20much easier to read and understand particularly if you have multiple outer joins.
    Brenden

  • Complex query/subquery/join problem

    Hi,
    i need to retrieve information from our database in one single dataset but i can't get it all together...
    Here's the situation:
    We have several linked tables:
    Workorder (wo_operation)
    -woo_key
    Workorder_task (wo_task)
    -wot_key -> PK
    -woo_key -> FK_woo
    Workorder_task_labor (wo_task_labor)
    -wtl_key -> PK
    -wot_key -> FK_wot
    -start_time -> essential field
    I'm running a query which retrieves records from the Workorder (wo_operation) table like this (this one works nicely, don't mind the other joins):
    SELECT
    rownum num,
    woo.woo_auto_key,
    woo.si_number,
    apc.application_code,
    cmp.company_name,
    woo.company_ref_number,
    view_wo.serial_number,
    view_wo.part_number,
    view_wo.description part_description,
    wos.description status_description
    FROM (((((wo_operation woo INNER JOIN view_spb_wo_maincomponent view_wo ON woo.woo_auto_key = view_wo.woo_auto_key)
    LEFT JOIN wo_status wos ON woo.wos_auto_key = wos.wos_auto_key)
    INNER JOIN parts_master pnm ON woo.pnm_auto_key = pnm.pnm_auto_key)
    INNER JOIN application_codes apc ON pnm.apc_auto_key = apc.apc_auto_key)
    INNER JOIN companies cmp ON woo.cmp_auto_key = cmp.cmp_auto_key)
    WHERE woo.wos_auto_key IS NULL OR woo.wos_auto_key not IN (2, 10)
    Now here's the problem. I need to add one more column which shows the last task (max(wo_task_labor.start_time)) that people have been working on (wo_task.description).
    Wo_task is linked to wo_operation on WOO_KEY (many TO one)
    Wo_task_labor is linked to Wo_task on WOT_KEY (zero or many TO one)
    So I need to find the MAX wo_task_labor.START_TIME and then Select the wo_task.description with that start_time. BUT since the relation is ZERO OR MORE to ONE it could be that there isn't even a START_TIME available for Max() function.......
    Is there anybody who could send me in the right direction???

    Hmmz ok, I just finished a more readable problem description.. Were you absolutely certain that my problem needs another approach?
    here's the problem again:
    Situation:
    wo_operation
    | Woo_auto_key | Si_number |
    | 1            | w100      |
    | 2            | w105      |
    | 3            | w200      |
    wo_task
    | Wot_auto_key | Woo_auto_key | Description |
    | 1            | 1            | OPENING     |
    | 2            | 1            | INSPECT     |
    | 3            | 2            | OPENING     |
    | 4            | 2            | REJECT      |
    | 5            | 3            | OPENING     |
    Wo_task_labor
    | Wtl_auto_key | Wot_auto_key | Start_time | Stop_time |
    | 1            | 1            | 7:00       | 7:05      |
    | 2            | 1            | 11:45      | 12:00     |
    | 3            | 2            | 10:00      | 10:15     |
    | 4            | 2            | 11:00      | 11:20     |
    | 5            | 2            | 11:35      | 11:40     |
    | 6            | 3            | 9:00       | 9:15      |
    | 7            | 3            | 9:30       | 9:40      |
    | 7            | 3            | 9:45       | 9:50      |
    | 8            | 4            | 9:00       | 10:00     |
    | 9            | 4            | 10:15      | 10:30     |
    Query:
    SELECT
         woo.si_number
    FROM
         wo_operation woo
    Result:
    | SI_NUMBER |
    | w100      |
    | w105      |
    | w200      |
    My needed result:
    | SI_NUMBER | DESCRIPTION      |
    | w100      | OPENING          | -> last labor is wtl_auto_key 2 from 11:45 to 12:00
    | w105      | REJECT           | -> last labor is wtl_auto_key 9 from 10:15 to 10:30
    | w200      | (null) or 'none' | -> last labor is not available since there is no labor record
    How can this be done querywise?
    Message was edited by:
    user574699

Maybe you are looking for