Using Two Outer Joins To Get A Record Count With Missing Records
Feb 5, 2008
Hello All,
I have three tables: Employees, Gender, Diversity. Both the Gender and Diversity tables are one to many relationships with the Employees Table. I am trying to run a query that will output a count of all diversities and genders. For example:
I am trying to get all counts, even if the combination of diversity/gender is not in the employees table. I am going to use that information in a Crosstab query.
What I thought would work was do a Left Join For Diversity and Employee such as:
SELECT Diversity.[Diversity Description], Count(Employee.ID) AS CountOfID FROM Diversity LEFT JOIN Employee ON Diversity.ID = Employee.Diversity GROUP BY Diversity.[Diversity Description];
Then, do a Left Join for Gender and Employee such as:
SELECT Gender.[Gender Description], Count(Employee.ID) AS CountOfID
FROM Gender LEFT JOIN Employee ON Gender.[Gender ID] = Employee.Gender GROUP BY Gender.[Gender Description];
And then do a Union. But that doesn't work.
Any thoughts or comments would be much appreciated!
I have this query in design view and in an asp page and it works fine:
SELECT dbo_feedback.*, dbo_origin.originName, dbo_product.prodname, dbo_category.catName FROM dbo_product INNER JOIN (dbo_origin INNER JOIN ((dbo_feedback INNER JOIN (dbo_category INNER JOIN links_cat ON dbo_category.catID = links_cat.CatID) ON dbo_feedback.id = links_cat.FeedbackID) INNER JOIN links_product ON dbo_feedback.id = links_product.FeedbackID) ON dbo_origin.originID = dbo_feedback.origin) ON dbo_product.prodID = links_product.ProductID;
BUT, I want to return all feedback entries, even if they have no matching Product or Category. :confused: When I change the inner joins to outer joins I get a syntax error in the browser window. I changed the join type in the relationship diagram in Access and tried to recreate this in query designer, but Access says the statement cannot be executed because of ambiguous outer joins.
FYI, one feedback can have many products, many categories, and only one origin. I have the joins correct and enforced.
Attached is a pdf of the query window showing the relationships and table structure; (sorry for the quality) the linkage is also permanent at the relationship window. I created a form (columnar) of Rooms; loaded a subform (columnar) of the projects; and then loaded the students (tabular) as a subform on the projects subform. The data entry is flawless; tabs through each field and form to form in sequence.
After entering several rooms data I tested it at the query level by loading the three tables: rooms, projects, and students, and the permanentely established linkage with junctions came in automatically. I thought I was home free--but when I run the query, I get zero records.
When I attempt various joins, thinking this will yeild all records from the many tables and their match, I get "ambiguous outer joins" and it says to run a separate query and add it to the SQL Statement?
Thanks for any help,
Almost funtional in Ann Arbor........
Oh, and thanks Pat Hartman for the tip on linkage -- although I may have screwed it up anyway.
I have made a database and have made a query that takes the info from the tables and creates a report. I have a subtable in the form and have added another sub table. When I try to add the new subtable info into the query for the report, I get "ambigous outer joins"??? What the heck is that?????
I'm new to the Access SQL world but I have a fairly complicated query that needs to be written for a project I'm working on. I am having trouble grasping the join concepts in access. My Query so far is:
SELECT u.user_logon_tx, ur.aff_sec_role_id, r.sec_role_ds, c.sec_cls_ds, o.sec_obj_ds, ci.aff_sec_cls_id, ci.sec_cls_item_ds, IIf(p.perm_in Is Null,0,p.perm_in) AS perm FROM aff_sec_cls_item AS ci, aff_sec_user AS u, aff_sec_role AS r, aff_sec_user_role AS ur, aff_sec_obj AS o, aff_sec_cls AS c, aff_sec_obj_item_role_perm p, ci LEFT OUTER JOIN p ON ci.aff_sec_cls_item_id=p.aff_sec_cls_item_id WHERE u.aff_sec_user_id=1 And ur.aff_sec_user_id=u.aff_sec_user_id And ur.aff_sec_role_id=r.aff_sec_role_id And o.aff_sec_obj_id=1155 And o.aff_sec_cls_id=ci.aff_sec_cls_id And o.aff_sec_cls_id=c.aff_sec_cls_id And ur.aff_sec_role_id=p.aff_sec_role_id And o.aff_sec_cls_id=p.aff_sec_cls_id And o.aff_sec_obj_id=p.aff_sec_obj_id;
I have gotten it to work by using just the tables I'm doing the outer join on but when I add everything else I get the Ambiguous Join error. I wish I was using Oracle Thanks for the help.
I have a database in which i am trying to create some forms in order to search for records. The database contains several tables. Some tables are linked using a compound key while others have a single PK. I created the search form which has different searching criteria. Once a user selects the criteria, they hit the search button (there are different buttons for each type of search) the button opens up a form to display all the data. The problem is that there are many tables to report on. I created a form with a subform. The tables associated with the main form are all being retrieved fine. however the subform doesn't seem to work. I created the subform using a query to select all the fields from the desired tables, i gave this query a criteria based on the main form so that the Id's would match. (ie. Main form ID = Firstable in subform.ID)
I got a blank sheet in the subform when i used the search. i presumed that my query was not pulling records because of the referential integrity rules. i went in and changed the relationship rules so that it would include all records from the first table and matching records from the second table. (middle option in the list when editing a relationship) I now get the following error when i try to run the query.
"The SQL statement could not be executed because it contains ambiguous outer joins. To force one of the joins to be performed first, create a separate query that performs the first join and then include that query in your SQL statement."
Could someone please tell me what this means as the help is... how shall we say it.. written in true Microsoft Fashion.
And though it tells me how to fix it, i'm not really sure what it's telling me to do. I am using Access2003 But the Database is in an access 200 file format.
Hi there. I have this query:SELECT [Range Plan 2006].[Parent Category] AS Expr1, [Range Plan 2006].Attribute AS [Sub category],[This Year All Prog].Category, [This Year All Prog].Product, [Description Master].Description, [This Year All Prog].SumOfQty AS [TY Cum Qty], [This Year All Prog].SumOfValue AS [TY Cum Value], [This Year All Prog].AvgOfMargin AS [TY Cum Margin],[Last Year All Prog].SumOfQty AS [LY Cum Qty], [Last Year All Prog].SumOfValue AS [LY Cum Value], [Last Year All Prog].AvgOfMargin AS [LY Cum Margin], [Last Year All Wk].SumOfQty AS [LY Wk Qty], [Last Year All Wk].SumOfValue AS [LY Wk Value], [Last Year All Wk].AvgOfMargin AS [LY Wk Margin], [This Year All Wk].SumOfQty AS [TY Wk Qty], [This Year All Wk].SumOfValue AS [TY Wk Value], [This Year All Wk].AvgOfMargin AS [TY Wk Margin], [Weekly Product Sales Analysis Stock].Qty AS [Total Stock], [Weekly Product Sales Analysis Stock].[Outstanding PO's], [Weekly Product Sales Analysis Stock].[Total Commitment] AS [Total Commit], IIf(IsNull([Product List - New].product),"",IIf(Year([Product List - New].[date entered])<Forms![Menu - Weekly Reports]!Year,"","NEW")) AS NEW, [Range Plan 2006].[Product Code] AS Expr2FROM [Range Plan 2006], ((((([This Year All Prog] LEFT JOIN [Last Year All Prog] ON [This Year All Prog].Product = [Last Year All Prog].Product) LEFT JOIN [Last Year All Wk] ON [This Year All Prog].Product = [Last Year All Wk].Product) LEFT JOIN [This Year All Wk] ON [This Year All Prog].Product = [This Year All Wk].Product) LEFT JOIN [Weekly Product Sales Analysis Stock] ON [This Year All Prog].Product = [Weekly Product Sales Analysis Stock].Product) LEFT JOIN [Description Master] ON [This Year All Prog].Product = [Description Master].Product) LEFT JOIN [Product List - New] ON [Description Master].Product = [Product List - New].Product;when I start it, access tells me that there are some ambiguous outer joins. I don't understand so much about outer joins, could you help me plz?Thanks.
My query references 2 related tables: one for persons (PERS) and one for telephone/fax numbers and email addresses (CONT, for Contacts). The relevant fields are:
The foreign key come_id refers to a table for contact methods (COME), either "Phone (Home)", "Phone (Work)", "Mobile", "Fax" or "Email".
Now i want to list all persons with their home phone number and email address, also if they don't have one. It seems to be impossible to get it ... I will explain what happens. Lets start simple: first list all persons with their home phone number (come_id = 1): SELECT PERS.pers_forename, PERS.pers_surname, CONT.cont_number AS Phone FROM PERS LEFT JOIN CONT ON PERS.pers_id = CONT.pers_id WHERE (((IIf(IsNull([come_id]),1,[come_id]))=1)); This works fine. The IIf expression is necessary since we are dealing with an outer join: not all persons have a home phone number. If we would simply put "WHERE come_id = 1" then the query produces only the persons that have a home phone number.
But now i also want to see the email address (come_id = 5): SELECT PERS.pers_forename, PERS.pers_surname, CONT.cont_number AS Phone, CONT_1.cont_number AS Email FROM CONT AS CONT_1 RIGHT JOIN (PERS LEFT JOIN CONT ON PERS.pers_id = CONT.pers_id) ON CONT_1.pers_id = PERS.pers_id WHERE (((IIf(IsNull([cont].[come_id]),1,[cont].[come_id]))=1) AND ((IIf(IsNull([cont_1].[come_id]),5,[cont_1].[come_id]))=5)); It seems perfectly logical: i added a second alias CONT_1 for the email address. Since this is also optional we have a second outer join, and the WHERE condition should also use an IIf expression. The result is not correct though: the resulting recordset shows only the persons that have both a home phone number and an email addres or neither! I have a lot of experience with SQL and queries, but i know i am not infallible. Nevertheless i am quite convinced that i should get all the persons: those that have a home phone number or an email address, or both or neither ... I hope that someone of you can explain this.
I have a fairly simple query to weed out all the records in our database that are missing vital pieces of infomation :
Code: SELECT Contacts.Name, Contacts.Address1, Contacts.Address2, Contacts.Town, Contacts.County, Contacts.Country, Contacts.PostCode, Contacts.Telephone, Contacts.Code FROM Contacts WHERE (((Contacts.Address1) Is Null) OR ((Contacts.Address2) Is Null) OR ((Contacts.Town) Is Null) OR ((Contacts.County) Is Null));
Is there anyway to count how many fields are missing for each record ?
I currently have query that looks at 2 tables that hold financial information. I am querying the data to do some adding and subtracting based off a financial class of a facility. The issue I am having is that one table may have a financial code that the other does not have but I still need to show that financial class for the facility.
My looks as follows
FROM [CashValue Link] INNER JOIN TCashValue ON ([CashValue Link].FINANCIAL = [TCashValue].FINANCIAL) and ([CashValue Link].Date1 = TCashValue.Date1) AND ([CashValue Link].FACILITY = TCashValue.FACILITY) AND ([CashValue Link].CLT = TCashValue.CLT)
This is an ongoing problem I have had for 4 weeks now.
I have made a a system thats acts like a clock In/clock out Out system.
the structure is somthing like this ID Username tblDailyLog TimeIn MorningBreakOut MorningBreakOut LunchOut LunchIn AfternoonOut AfternoonIn TimeOut
All fields apart from ID (autonumber) and username (String*255) are Date field (there are a few others like DateOfTimesheet etc but they arnt important here)
When a user arrives in the morning they make a record which they use for the day
They then have a form with a whole bunch of buttons which simply updates the correct field. For example they click the "Sign in for the Day" button and it updates the correct field with the current time.
Everything was going fine until people noticed that every now and again a sign in time dissapeared.
I have hacked myself to death trying to solve this problem but still the updates go Astray.
Now each time a time is updated the process goes somthing like this
1. the user opens their timesheet for the day (the RS is SNAPSHOT and no locks)
2. User Hits a sign in/out button 3. The record source is changed to "" and all buttons hidden (to ensure the record isnt locked and to make sure you dont do two things at once) 3. The table is updated with the new time (using some dynamic SQL) 4. The table is repeatadly checked using a DO loop to make sure the the correct time went in. 5. when the returned time value of the field matches the varaible used to update it, the form is returned to normal and the user carries on his/her merry way (if it never matches the screen should crash but this never happens). 6. A New record is added to another table called "tblbugfixinglog" which records which field was updated and when. This is so that I have two records in two different ways (figured if one went astray I could pull it back off the other) 7. Another new record is added to yet another table called tblSQLRecord, which simply logs all .RUNSQL statements that are executed.
I thought that the two extra tables (and the check that the record had been updated) would help me track down where the records are going missing, but this isnt the case.
Now it appears that some records arnt being added to tblBugFixingLog and to tblSQLRecord either and some of these tables are getting quite a few #ERROR's in them..
None of the tables are related to any other and i've no idea how #ERROR lines are appearing in a table that has 1 function... to recieve new records ... no editing, no viewing, no deleting.
Does anyone have any idea how these updates/inserts can go missing or create #ERRORs. I've built plenty of Databases in my time and have never come across this. __________________________________________________ ______________
This is the function I use to add a record to tblBugfixingLog and tblSQLRecord
Private Sub AddBugLog(ByVal TimesheetNumber As Long, ByVal FieldUpdating As String, ByVal NewFieldValue) Dim TempSQL As String TempSQL = "INSERT INTO tblBugFixingLog (TimeAndDateOfEntrySERVER,TimeAndDateOfEntryPC,Fie ldUpdated,NewEntry,UserID,TimesheetNumber,Computer AssetNo) VALUES (" & _ "#" & Format(ServerGetTime(Environ$("LOGONSERVER"))) & "#," & _ "#" & Now & "#," & _ "'" & FieldUpdating & "'," & _ "'" & NewFieldValue & "'," & _ "'" & GetNTUser & "'," & _ "'" & TimesheetNumber & "'," & _ "'" & fOSMachineName & "')" ' MsgBox TempSQL DoCmd.RunSQL "INSERT INTO tblSQLRecord (Username,DateAndTime,Screen,TheSQL) VALUES('" & LoginInfo.sUsername & "','" & CStr(Now) & "','Add Bug Log function','" & CleanData(TempSQL) & "')", False 'CleanData is a function that removes ' and " from the SQL string so i can easily add the SQL string into the table DoCmd.RunSQL TempSQL, False End Sub
Public Function CleanData(ByVal DataToClean As String) Dim TempData As String Dim i As Integer TempData = "" For i = 1 To Len(DataToClean) Select Case Mid(DataToClean, i, 1) Case "'" TempData = TempData & "`" Case """" TempData = TempData & "`" Case Else TempData = TempData & Mid(DataToClean, i, 1) End Select Next i CleanData = TempData End Function
I modified a form and now it seems it's impossible to modify/add records. It seems that all comes from when I modified my record source query to add a a field in which it COUNTs all related records in another table. Now the form can't modify anything else but I need to change other fields or add new records! In other words: how can I add a simple box which, for every record of my table/form, counts the number of related records in another table (relationship is 1-to-many, and of course is based on a field in table2) letting me modify and add records? Thank you
I have a simple nested query that is not working as expected. My inner query returns 102 records but when I run with outer query I only get 96 records. Below is my query, I don't really want to pull the same fields from both tables but I was doing to test. The values that are missing are those that don't exist with the monthenddate 8/31/2014 - a left join should fix that but doesn't seem to be working ..
Code:
Select distinct a.entity, a.gl_account,a.profit_center,[Open Items_1].profit_center,[Open Items_1].gl_account,[Open Items_1].entity from( SELECT DISTINCT [Open Items].entity, [Open Items].gl_account, [Open Items].profit_center FROM [Open Items] )a left outer JOIN [Open Items] AS [Open Items_1] ON (a.profit_center = [Open Items_1].profit_center) AND (a.gl_account = [Open Items_1].gl_account) AND (a.entity = [Open Items_1].entity) Where ([Open Items_1].MonthEndDate=#8/31/2014#)
i do a query and outer join this table with a query and it produces LESS records = 3733
:confused:
now i always assumed (never assume it makes an "ass" out "u" and "me" !) that the records would be the same as the table you were joining from, obviously i've assumed wrongly, but why?
the query i'm using as my lookup query is grouped and i think that is causing me problems...if i turn it into a table, it works as expected
:confused:
and i check the obvious: no filters or SELECT DISTINCT...
I have a list of PC SN#s in tbl1; I have a list of other PC SN#s in tbl2 I want to display ALL records of tbl1, AND ALL records of tbl2, matching up the SN#s (where there is a match) - but I want to display all records whether they match or not.
In this table it has a bookingID, CustomerID and some other none relevant details.
The CustomerID comes from table tblCustomer. i.e a customerID must exist in the customer table to be allowed in the bookings table tblBookings
A customer can exist in tblCustomer without existing in the booking table.
I am trying to write a query that will list each and every customer ID in the tblCustomer and count the number of bookings that that customer has (even if it is zero).
I have a query that will count the bookings if they exist in the booking table and display the number of times that a customer appears in the bookings table.
SELECT tblBookings.CustomerID, Count(tblBookings.CustomerID) AS NoOfBookings FROM tblBookings GROUP BY tblBookings.CustomerID;
How do I create a query that will do this but list all customers even if they don't exist in the bookings table (but obviously occur in the customers table)
I am trying to create a similar query where all bookings per hotel are listed even if no bookings are made for that hotel. I am guessing the answer is the same as above.
The Ritz. Bookings 0 The Hilton. Bookings 3 The Carlton. Bookings 0 The Lowry. Bookings 2
The journal ID above was an accounting entry, debit $16,797 and credit $-16,797. because it was entered as a reversing journal in the system, the table has captured the Journal ID with 2 dates. For my purpose i only want the one date (MIN) date, the total amount of the journal (either the debit or credit amount 16,797) and the total number of lines the journal ID has so in this instance I want the count to be 2 and not 4.
Im thinking with the total sum because theres debits and credits is there a way to do the absolute value of the journal MONY_A then divide by 2?
current SQL SELECT [One Year Data Lines].JRNL_I, [One Year Data Lines].CNCY_C, Count([One Year Data Lines].JRNL_I) AS CountOfJRNL_I, Min([One Year Data Lines].JRNL_D) AS MinOfJRNL_D, [One Year Data Lines].BUSN_UNIT_I, Sum([One Year Data Lines].MONY_A) AS SumOfMONY_A FROM [One Year Data Lines] GROUP BY [One Year Data Lines].JRNL_I, [One Year Data Lines].CNCY_C, [One Year Data Lines].BUSN_UNIT_I HAVING ((([One Year Data Lines].JRNL_I)="0002888269") AND (([One Year Data Lines].CNCY_C)="aud"));
I just restructured my DB and I was wondering if anyone can give me some advice on whether or not my joins/relations are correct. I left some joins/relations out because I wasn't sure what relation I should use.
I have a weird situation and I was wondering if anyone has had an issue with this. I have a record missing from a table. Normal Users are not allowed to delete records from the Form view. There is a blank record where the record should be. The auto number counts from 37, 38, 40. Record 39 is missing and there are blanks where it should be. The autonumber field is my Primary Key and it is blank just like the rest of the fields in the record. I know that the record existed at one time because one of the DB users has a report referencing that record. Any Ideas?
I hope this is the right section for posting this Q.
I use Access 2003 on WinXP pro as front-end & for back-end a MySql on a Linux server. I use MyODBC to connect to the back-end and all the tables are on the back-end. The workstation is connected to the server via VPN (so the server and the station are on different locations).
Quite often I get a problem that not all records are inserted into a table. E.g. I have like 5 - 15 records (up to 10 fields) in one table and I want to transfer/copy them to another:
Hello people. Iam having a problem and i need some help. iam appending data in one table to data in another another. I have two tables(table1 and table2), with the same fields but the records in one table2 are 5 more than those in table1 which are 3. The 3 records in table1 are also in table2. I would like a query which outputs the other 2 records that are in table2 and not in table1.
i have a query that contains two tables one contains the member details the other their transactions. the query is to show all members and transactions however if there is no transaction then the member details do not show - -the query only shows members with transactions . the query does have grouping to give totals of the transactions
I made a query that calculates the sum of from a table that contains defect types and numbers.
The problem is when after the inspection there's no defect no values will be entered in the mentioned table. And running the query the result is 'NOTHING'.
I tried to deal with this 'nothing' putting this in another query:
I want to set up that if there is missing value of the fields, then we cannot go to next record or exit the form when we click to do next action.
I tried to add the code in the After update event, or Exit event,
Example Code: if (isnull([Zip]) or len([zip]) = 0) then msgbox "missing" [zip].setforce end if
when I click to go to next record, or exit the form, it give out message "missing", it work fines, but, it still go to next record, or exit the form after the message.