How to return only non matching left join records. Currently I am doing a traffic management database to learn sql.
I am checking for all parishes with no associated drivers. Currently I only have 2 of such.
The regular left join
select parish.name, driver.fname from parish left join driver on driver.parish=parish.name
Returns the all the names of the parishes and the first name of the associated drive, followed by the matches, however the two parishes with no matches have null for the first name.
create table a (id int, name varchar(10)); create table b(id int, sal int); insert into a values(1,'John'),(1,'ken'),(2,'paul'); insert into b values(1,400),(1,500);
select * from a cross apply( select max(sal) as sal from b where b.id = a.id)b;
Below is the result for the same:
idname sal 1John500 1ken500 2paulNULL
Now I'm not sure why the record with ID 2 is coming using CROSS APPLY, shouldn't it be avoided in case of CROSS APPLY and only displayed when using OUTER APPLY.
One thing that I noticed was that if you remove the Aggregate function MAX then the record with ID 2 is not shown in the output. I'm running this query on SQL Server 2012.
I have a strange request that might not be possible based on the laws of relational databases but I thought I'd give it a try.
I have three tables which for simplicity I will call A, B and C. Table A contains my master records, Table B contains user details and the final table contains some extra data
In my initial search when joining A and B, I return 100 records. I then need to search in table C for these 100 records based on a criteria. the expected result should return all 100 rows for the ones that match and also the ones that do not match. The problem is that in Table C, not all the 100 IDs exist, so there will not be a corresponding record. Unfortunately, our users still want to see all 100 records in the output. Is this possible
As always any help or direction would be appreciated.
SELECT [tblSections].[pageTitle], [tblSections].[sectionURL], [tblSectionContents].[articleID], [tblSectionContents].[fileID], [tblSectionContents].[linkID], [tblCopy].[copyText], [tblFiles].[fileName], [tblFiles].[fileCaption], [tblGroupings].[grouping], [tblLinks].[linkURL] FROM [tblSections] LEFT JOIN [tblSectionContents] ON [tblSectionContents].[sectionID] = [tblSections].[id] LEFT JOIN [tblCopy] ON [tblSectionContents].[articleID] = [tblCopy].[id] LEFT JOIN [tblFiles] ON [tblSectionContents].[fileID] = [tblFiles].[id] LEFT JOIN [tblGroupings] ON [tblFiles].[groupingID] = [tblGroupings].[id] LEFT JOIN [tblLinks] ON [tblSectionContents].[linkID] = [tblLinks].[id] WHERE [tblSections].[id]=2 ORDER BY [tblSectionContents].[articleID], [tblSectionContents].[fileID], [tblSectionContents].[linkID]
If I pass it the ID of a section that has files or copy or [stuff in other tables] attached, then I get a result set that makes sense.
But if I pass it a section ID that doesn't reference any other content tables (ie: the section just has a title and a link URL), I don't get anything back.
Shouldn't it should still get me the fields from the row in tblSections that matches the ID I'm passing it?
I have a SELECT Statement that I am using that is pulling from two tables. There won't always be results in the second table so I made a LEFT OUTER JOIN. The problem I am having is that I need to have three conditions in there:WHERE (employee.emp_id = @emp_id) AND (request.requested_time_taken = 'FALSE') AND (request.request_end_date >= GETDATE()))The two conditions from the request table are causing the entire query to return NULL as the value. I need help trying get a value whether or not there are any results in the request table.Here is the full select statement:SELECT (SELECT SUM(ISNULL(request.request_duration, '0')) AS Expr1 FROM employee LEFT OUTER JOIN request AS request ON employee.emp_id = request.emp_id WHERE (employee.emp_id = @emp_id) AND (request.requested_time_taken = 'FALSE') AND (request.request_end_date >= GETDATE())) AS dayspending FROM employee AS employee_1 LEFT OUTER JOIN request AS request_1 ON employee_1.emp_id = request_1.emp_id WHERE (employee_1.emp_id = @emp_id) GROUP BY employee_1.emp_id, employee_1.emp_begin_accrual, employee_1.emp_accrual_rate, employee_1.emp_fname, employee_1.emp_minitial, employee_1.emp_lname
I'd like to return the following result set: CompanyModules.CompanyID | Modules.Name | Present 1 | A | True 1 | B | True 1 | C | True 2 | A | True 2 | B | False 2 | C | False
What would be the query for this? Thanks.
Edit: This is the query I have tried:
select CompanyModules.CompanyID, Modules.Name, count(Modules.ID) as Present from
CompanyModules RIGHT outer Join Modules on CompanyModules.ModuleID = Modules.ID
group By CompanyModules.CompanyID, Modules.Name
Order by CompanyID
However, it only returns a partial result set:
CompanyModules.CompanyID | Modules.Name | Present 1 | A | 1 1 | B | 1 1 | C | 1 2 | A | 1
Hi folks. Thanks for the opportunity to get a bit of help here.
I've got two tables. Say, table "foo" and table "bar". I LEFT JOIN them on a key, say, foo.id and bar.fooid.
For some reason, when I do this join, I get only records from "foo" which have a mate in "bar".
What I really need is all records from "foo", but the columns from bar when there is a match. I don't want to exclude records from "foo" just because they don't have a match from "bar".
I have 2 tables GLSUMMARY and GLBUDGET, they are identical. I am joining them together with a left outer join from the SUMMARY to the BUDGET but when I dont have a matching BUDGET record on the join the SUMMARY gets dropped as well :eek:
Any help will be appreciated!
Here is the query! SELECT s.conu as CoNu, s.deptnu as DeptNu, s.fundnu as FundNu, s.acctnu as AcctNu, Sum(isNull(Amt01,0)) as Amt01, Sum(isNull(Amt02,0)) as Amt02, Sum(isNull(Amt03,0)) as Amt03, Sum(isNull(Amt04,0)) as Amt04, Sum(isNull(Amt05,0)) as Amt05, Sum(isNull(Amt06,0)) as Amt06, Sum(isNull(Amt07,0)) as Amt07, Sum(isNull(Amt08,0)) as Amt08, Sum(isNull(Amt09,0)) as Amt09, Sum(isNull(Amt10,0)) as Amt10, Sum(isNull(Amt11,0)) as Amt11, Sum(isNull(Amt12,0)) as Amt12, Sum(isNull(Amt13,0)) as Amt13, Sum(isNull(Bud01,0)) as Bud01, Sum(isNull(Bud02,0)) as Bud02, Sum(isNull(Bud03,0)) as Bud03, Sum(isNull(Bud04,0)) as Bud04, Sum(isNull(Bud05,0)) as Bud05, Sum(isNull(Bud06,0)) as Bud06, Sum(isNull(Bud07,0)) as Bud07, Sum(isNull(Bud08,0)) as Bud08, Sum(isNull(Bud09,0)) as Bud09, Sum(isNull(Bud10,0)) as Bud10, Sum(isNull(Bud11,0)) as Bud11, Sum(isNull(Bud12,0)) as Bud12, Sum(isNull(Bud13,0)) as Bud13 FROM shelbydb.shelby.GLSummary S left OUTER JOIN shelbydb.shelby.GLBudget B on (s.begindate = b.begindate) and (s.acctnu = b.acctnu) and (s.conu = b.conu) and (s.deptnu = b.deptnu) and (s.fundNu = b.fundNu) WHERE (s.begindate = '1/1/2004' and b.begindate = '1/1/2004') group by S.conu, S.deptnu, S.fundnu, S.acctnu, b.conu, b.deptnu, b.fundnu, b.acctnu
SELECT * FROM a LEFT OUTER JOIN b ON a.id = b.id instead of
SELECT * FROM a LEFT JOIN b ON a.id = b.id
generates a different execution plan?
My query is more complex, but when I change "LEFT OUTER JOIN" to "LEFT JOIN" I get a different execution plan, which is absolutely baffling me! Especially considering everything I know and was able to research essentially said the "OUTER" is implied in "LEFT JOIN".
I need to use a self join on a table to get it to return one line item ofr all of the line items within the table. The subscriptions table has many line items containing product code. I need to eb able to return one line item containing each of the different product codes.
I was writing a query using both left outer join and inner join. And the query was ....
SELECT S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname FROM Production.Suppliers AS S LEFT OUTER JOIN (Production.Products AS P INNER JOIN Production.Categories AS C
[code]....
However ,the result that i got was correct.But when i did the same query using the left outer join in both the cases
i.e..
SELECT S.companyname AS supplier, S.country,P.productid, P.productname, P.unitprice,C.categoryname FROM Production.Suppliers AS S LEFT OUTER JOIN (Production.Products AS P LEFT OUTER JOIN Production.Categories AS C ON C.categoryid = P.categoryid) ON S.supplierid = P.supplierid WHERE S.country = N'Japan';
The result i got was same,i.e
supplier country productid productname unitprice categorynameSupplier QOVFD Japan 9 Product AOZBW 97.00 Meat/PoultrySupplier QOVFD Japan 10 Product YHXGE 31.00 SeafoodSupplier QOVFD Japan 74 Product BKAZJ 10.00 ProduceSupplier QWUSF Japan 13 Product POXFU 6.00 SeafoodSupplier QWUSF Japan 14 Product PWCJB 23.25 ProduceSupplier QWUSF Japan 15 Product KSZOI 15.50 CondimentsSupplier XYZ Japan NULL NULL NULL NULLSupplier XYZ Japan NULL NULL NULL NULL
and this time also i got the same result.My question is that is there any specific reason to use inner join when join the third table and not the left outer join.
OLEDB source 1 SELECT ... ,[MANUAL DCD ID] <-- this column set to sort order = 1 ... FROM [dbo].[XLSDCI] ORDER BY [MANUAL DCD ID] ASC
OLEDB source 2 SELECT ... ,[Bo Tkt Num] <-- this column set to sort order = 1 ... FROM ....[dbo].[FFFenics] ORDER BY [Bo Tkt Num] ASC
These two tasks are followed immediately by a MERGE JOIN
All columns in source1 are ticked, all column in source2 are ticked, join key is shown above. join type is left outer join (source 1 -> source 2)
result of source1 (..dcd column) ... 4-400-8000119 4-400-8000120 4-400-8000121 4-400-8000122 <--row not joining 4-400-8000123 4-400-8000124 ...
result of source2 (..tkt num column) ... 4-400-1000118 4-400-1000119 4-400-1000120 4-400-1000121 4-400-1000122 <--row not joining 4-400-1000123 4-400-1000124 4-400-1000125 ...
All other rows are joining as expected. Why is it failing for this one row?
Why would I use a left join instead of a inner join when the columns entered within the SELECT command determine what is displayed from the query results?
Why does this right join return the same results as using a left (or even a full join)?There are 470 records in Account, and there are 1611 records in Contact. But any join returns 793 records.
select Contact.firstname, Contact.lastname, Account.[Account Name] from Contact right join Account on Contact.[Account Name] = Account.[Account Name] where Contact.[Account Name] = Account.[Account Name]
And by correctly, I mean the way it *should* match, of course.I've got 2 data sources, using a left outer join, matching 2 columns. Whatever is the right side of my table is never matching and returning data. Here's my basic setup:OLE DB Source 1 (table1) Sel Name Order JoinKeyno UniqueID 1 yesyes Column1 0 no ...
OLE DB Source 2 (table2) Sel Name Order JoinKeyyes ID 1 yesyes Columns 0 no ...
There is a link (arrow) between UniqueID and ID, and the join type is "Left Outer Join". When I execute the statement "SELECT * FROM Table1 LEFT JOIN TABLE2 ON TABLE1.UniqueID = Table2.ID", the data returns correctly to me. What am I missing with the properties I've set above with the merge join?
I have been assigned to write a report that queries 3 tables. Table Store, Store_ID unique index, Cust table Cust_ID non unique index, CUST_Store_ID relates to Store Table, Table Emp, Emp_ID non unique index, Emp_Store_ID relates to Store Table
The problem is that the Employes and the customer don't relate to each other in any way. There can be stores with no Employees and there can be stores with no Customers. There are employees and customers listed multiple times in thier respective tables, and the multiple listings need to show on the report. A result set may look like this.
Hi, This is a where clause I am using in a search. WHERE (ADDRESS_STREET LIKE '%' + @Search + '%' ) I am trying to do a search which returns the most matching record. For example if I have a record with Denver as text . If I search for Denvr the spell error is intended , I will not get the result. How can I create a stored procedure to counter probable spelling errors and return matching results in a ranked order. Thanks
Init SC --- 89 Post NCOA --- 89 Post Supp --- 89 Revised Final State Counts --- 89 Revised Final State Counts --- 94 ***********************************************************************************************
Since "Revised Final State Counts" appears in both cycles 89 & 94. How can I query the table so that I only get that 1 record?
SELECT EventID, Role, EventDuty, Qty, StartTime, EndTime, Hours FROM dbo.tblEventStaffRequired;
and SELECT EventID, Role, StartTime, EndTime, Hours, COUNT(ID) AS Booked FROM tblStaffBookings GROUP BY EventID, Role, StartTime, EndTime, Hours;
How can I join the results of the two by matching the columns EventID, Role, StartTime and EndTime in the two and have the following columns in output EventID, Role, EventDuty, Qty, StartTime, EndTime, Hours and Booked?
SELECT task1_.Start as y0_, count(this_.FirstName) as y1_ FROM t_contact this_ inner join t_task task1_ on this_.TaskId=task1_.Id GROUP BY task1_.Start
There is something I don't understand. When I use join
SELECT r.CHECK_NUMBER, i.orig_file from (AP_INVOICEDOCS i join AP_DETAIL_REG r on r.PAYABLE_ID= i.PAYABLE_ID)
I am getting 76 orig_file records
But when I do
SELECT r.CHECK_NUMBER, i.orig_file from (AP_INVOICEDOCS i right outer join AP_DETAIL_REG r on r.PAYABLE_ID= i.PAYABLE_ID)
I am showing only 8 records under i.orig_file column and I am not sure why. What I need is to get all the AP_INVOICEDOCS in the matching orig_file records.
I'm trying to join 2 tables. I thought I was getting the correct results but it turns out I'm not. My Query: SELECT IVINVA, IVORDN, IVCSLN, IVRESR, IVCITM, CONVERT(varchar(12),CAST(IVIAMT as money),1) AS ExtPrice, CONVERT(varchar(12),CAST(IVPIVC as money),1) AS DistPrice, IVCSUM, IVQYCS, IVDESC, OIRESR, OIDPCT, CONVERT(varchar(12),CAST(IVPIVC - (OIDPCT / 100 * IVPIVC) as money),1) AS NetPrice FROM INVDET1_TBL LEFT JOIN ORDDIS_TBL ON ORDDIS_TBL.OIORDN = INVDET1_TBL.IVORDN AND ORDDIS_TBL.OIRESR = INVDET1_TBL.IVRESR WHERE IVORDN = '0859919' AND IVINVA = '00324024' Basically, my problem lies in the seonc condition of the LEFT JOIN. I needed to set the two tables equal my item number, because in some situations I need that logic to get the correct result. It most other cases, that item column in the ORDDIS_TBL is NULL, thus giving me the wrong results. In that case, I would want the JOIN to only be ORDDIS_TBL.OIORDN = INVDET1_TBL.IVORDN, and not include the second part. Is there a way I can condition this with an If statement, If ORDDIS_TBL.OIRESR is Null then do this join, if not, then do this? I'm confused how to get the proper result here.
3) select p.komorka,isnull(sum(ustalenia),0) from #plantemp p left join analiza_1 a on p.komorka=a.komorka where a.koniec between '20040701'and '20040731' group by p.komorka
komorka ustalenia (sum)
08.0000 SI/1788138.9300 SI/262856.8900
I need all rows from table 1 bat right and left join gives me the same results, WHY
As you can see the ParentIndexID and ChildIndexID fields refer to tblIndices.IndexID I would like a stored procedure as follows: show all index names and show the wights for the indexID you passed. This is what I have so far and it is not correct yet. Not sure what the syntax should be.
alter PROCEDURE [dbo].[uspBasketIndices_Get]
@IndexIDint
AS
select i.IndexID, i.[Name], bc.Weight from tblIndices as i left join tblBasketConstituents as bc on i.IndexID = bc.ParentIndexID and i.IndexID = @IndexID order by i.[Name]
Any one know any facts and figures about maximum Left Joins allowed (or recommended) in one query?
I am running a MS SQL 2000 my database is full of relational data and most of my foreign keys (INT data type) are a Clustered Indexed, Usually I will only be pulling one record from collection of about a dozen tables, but the Database is expected to grow fast and become big.
Right now I have a Stored Proc that has eight(8) LEFT JOINs in it. My worry is that this query will kill me as the database approaches 50,000 records.
Hi all. My query works fine, it generates reports but not my expected result.
select d.fullname, p.nickname, p.birthdate, p.birthplace, p.gender, p.civilstatus, p.religion, p.nationality, p. weight, p.height, p.haircolor, p.eyecolor, p.complexion, p.bodybuilt, p.picture, p.dialectspoken, d.mobilephone, d.prprovince,[Age] = dbo.F_AGE_IN_YEARS( birthdate, getdate() ), c.name, c.address, c.telno, c.email, c.occupation, ed.year1, ed.year2, ed.degree, sch.schname from hremployees as e inner join psdatacenter as d on e.empdcno = d.dcno inner join pspersonaldata as p on e.empdcno = p.dcno left join hrappempcharrefs as c on e.empdcno = c.empdcno left join hrappempeducs as ed on e.empdcno = ed.empdcno left join hrsetschools as sch on ed.schoolcode = sch.schcode
the above query gives a 77 records
if i ran "select * from hremployees" generates 60 records
i think the error is in the left joining. hrappempcharrefs, hrappempeducs and hrsetschools must be left joined to hremployees.