This is my query:-
SELECT DISTINCTROW Customer.custName, Sum(Invoice.invAmount) AS SumOfinvAmount, Sum(Payment.payAmount) AS SumOfpayAmount
FROM (Customer LEFT JOIN Invoice ON Customer.custID = Invoice.invCustID) LEFT JOIN Payment ON Customer.custID = Payment.payCustID
GROUP BY Customer.custName, Customer.custID;
Result:-
custName SumOfinvAmount SumOfpayAmount
blake $20.00
julie $50.00
kate $375.00 $290.00
steven $200.00
The resulting SQL query returns incorrect invoice and payment totals for Kate. The Sum() function has duplicated. Can anyone tell me how I would change my query to fix this problem?
ContentTypes ---> Site Content Directory Cats ---> Categories Sierra ---> Store Content for Sierra BrushStrokes ---> Store Content for BS
I have "tried" to create a QUERY for the 4 Tables (The code that I have, originally came with 3-Table Query connection I have added in the 4th Table "BrushStrokes")
This is the Query that I created. Before the code, a little insite
At first there was: RIGHT & LEFT JOIN's, But I would receive this: Error 3258 After not really finding any good examples of how to create the 2- Queries and have then work together as one. I decided to try something else, which was to create all [INNER JOIN]'s Which got rid of the Error, and the code still will not work in my site. ======== Microsoft JET Database Engine error '80040e14' Syntax error in JOIN operation. =======
So, here is the code, please let me know what is wrong with it? And if possible, a good example of creating the [2 - Queries] that work as one.
Thank you all Carrzkiss -----------------------SQL QUERY------------------ SELECT Cats.CatID, Sierra.CatID, BrushStrokes.CatID, Sierra.ContentID, BrushStrokes.BSContentID, Sierra.Product_Title, BrushStrokes.BSProduct_Name, Cats.CatDescription, Cats.CatTypeId, Sierra.Product_Th_Image, BrushStrokes.BSThumbnail, Sierra.Our_Price, BrushStrokes.BSPrice, Sierra.Retail_Price, BrushStrokes.BSRetail, Sierra.Aff_Name, BrushStrokes.Aff_Name, Sierra.Brand_Name, BrushStrokes.BSArtistName, Sierra.YAvailable, BrushStrokes.BSStatus, Sierra.Percent_Savings, Sierra.Unique_Product_ID, BrushStrokes.BSProductID, Sierra.Main_Cat, BrushStrokes.BSCol_Cat, ContentTypes.ContentType, Sierra.Product_Description, BrushStrokes.BSDescription FROM ((ContentTypes INNER JOIN Sierra ON ContentTypes.ContentTypeID = Sierra.ContentTypeID) INNER JOIN BrushStrokes ON ContentTypes.ContentTypeID = BrushStrokes.ContentTypeID) INNER JOIN Cats ON (BrushStrokes.CatID = Cats.CatID) AND (Sierra.CatID = Cats.CatID) WHERE (((Sierra.Display)=1) AND ((BrushStrokes.Display)=1)); -----------------------------END SQL QUERY------------------
Here is my current table structure (I have omitted some fields from this example and have given some sample data in italics to make the table structure more clear.
tblEmployees
ID (autonumber) 3 EmployeeName John EmployeePhone 555999555 EmployeeLocation New York
tblClients
ClientID (autonumber) 1 , 2 , 3 ClientName ABC Company , XYZ Company, PQR Company fkeyLocationID
tblLocations LocationID 1 , 2 Location New York , Chicago
The junction table tblEmployeeClients only stores ID of the Employee and in the second column (which is a multi-valued field), the ID of each of the clients the employee Supports.
I am trying to generate a report that lists say, EmployeeName alongside the clients supported by the Employee (listing the client location is not required, however, it would be good to know how to do that as well).
The report (for the example above), should look like this:
Name Clients Supported John ABC Company, PQR Company
Currently, I am able to get :
John 1, 2 i.e the client ID for the clients that the employee supports instead of the corresponding company names.
Multiple IF functions in a form. I have a button that on click will print a report if certain fields in the form have data in them. If not, a msgbox pops up to let the user know that data must be filled and then sets focus on whichever field needs data in the form. There are many IF statements, and they all work fine until I get to a certain one then the remaining IF does not continue.
Here is some code:
If IsNull([Alert]) Then MsgBox "An alert time is required." _ , vbCritical, "Data Required" Me.Text591.SetFocus Exit Sub Else If IsNull([Enroute]) Then
[Code] .....
The next IF argument will bring up the msgbox when there is no data, thats great. However, when the user fills in the field and continues with the button click to print the report, the button does nothing.
Here is the next IF, the one with the problem:
If IsNull([Combo608]) Then If IsNull([Combo620]) Then MsgBox "You must select either a planned event or an emergency event." _ , vbCritical, "Information" Me.Combo608.SetFocus Exit Sub Else
How to get it to work, to continue with the remaining IF arguments after this one (there are several more)?
Or are there a better way to code this and not have the many IF arguments?
Any way to use multiple count functions in a query with their own individual filters without affect the others?
For example:
SELECT [E&I Table].System, [E&I Table].DeleteRecord, Count([E&I Table].[Status#1]) AS [CountOfStatus#1], Count([E&I Table].[Status#2]) AS [CountOfStatus#2] FROM [E&I Table] WHERE ((([E&I Table].[Status#1]) Like "ITR Rcv'd by QA" Or ([E&I Table].[Status#1]) Like "Completed" Or ([E&I Table].[Status#1]) Like "Ready for T/O" Or ([E&I Table].[Status#1]) Like "Reviewed by JVV") AND (([E&I Table].[Status#2]) Like "ITR Rcv'd by QA" Or ([E&I Table].[Status#2]) Like "Completed" Or ([E&I Table].[Status#2]) Like "Ready for T/O" Or ([E&I Table].[Status#2]) Like "Reviewed by JVV")) GROUP BY [E&I Table].System, [E&I Table].DeleteRecord;
I am trying to count in each column of the E&I table with criteria using WHERE but the problem is when you have more than 1 WHERE it affects the other columns as well... tried a bunch of different ways and I am now having to create seperate Queries than combine them using another Query...
I have a table that is basically a survey form. The same series of options was available for 35 questions, and the table used to have a text string written for each answer. Because of all the repetitive data, I created a second table that assigned a number value to each of the nine possible options in these 35 separate fields. What happened is that, instead of the same text strings repeated over and over (and taking up real estate), now each of the 35 columns had a single number in them.
Now comes the day of reckoning and TPTB want a query with the raw data and the original text strings back in instead of the numbers. I was thinking doing something along the lines of a DLookup, but I can't seem to make that work in a query correctly. Apart from calling the same table and linking it over and over to the different fields in the original data table (see photo for how insane that is).
I am working on a "course registration" system using asp (vbscript) and MS Access. There are 4 tables as shown:
activity (1 entry per course - key is ActivityID)
activitysections (1 entry for each course section for an activity - key is SectionID - ActivityID is also in the record)
registrations ( 1 entry for each registrant in the section - key is RegistrationID - Section ID and PersonID are also in the record)
users ( 1 entry for each student with their demographic info - PersonID is the key)
When I run the following query on the test Access database:
SELECT activity.ActivityName, activity.ActivityStatus, activity.ActivityID, activitysections.SectionNumber, activitysections.SectionStatus, activitysections.SectionSchedule, activitysections.SectionCapacity, activitysections.SectionParticipants, activitysections.SectionDuration, users.FirstName, users.Initial, users.LastName, users.NameSuffix, users.PreferredName, users.Gender, users.BirthDate FROM users INNER JOIN ((activity INNER JOIN activitysections ON activity.ActivityID = activitysections.ActivityID) INNER JOIN registrations ON activitysections.SectionID = registrations.SectionID) ON users.PersonID = registrations.PersonID;
I get the correct results - 1 entry wherever there is a registrant for a section of an activity.
However, I want to run a query that lists all the sections regardless of whether there is a person registered. To do that I changed the query to a left join as follows:
SELECT activity.ActivityName, activity.ActivityStatus, activity.ActivityID, activitysections.SectionNumber, activitysections.SectionStatus, activitysections.SectionSchedule, activitysections.SectionCapacity, activitysections.SectionParticipants, activitysections.SectionDuration, users.FirstName, users.Initial, users.LastName, users.NameSuffix, users.PreferredName, users.Gender, users.BirthDate FROM users INNER JOIN ((activity INNER JOIN activitysections ON activity.ActivityID = activitysections.ActivityID) LEFT JOIN registrations ON activitysections.SectionID = registrations.SectionID) ON users.PersonID = registrations.PersonID;
I get this wonderful little message saying "join expression not supported". Can anyone give me some advice on what I am doing incorrect. Thanks.....
Orders ====== OrderID = AutoNumber OrderDate = Date/Time OrderInfo = Memo CustomerName = Text CustomerAddress = Text PaymentDetails = Text
OrderProductDetails ========= OrderNumber = Number (Linked to OrderID) ProductNumber = Number (Linked to ProductID) Notes = Memo (Notes on product customization)
The OrderProductDetails table is in many to one relationships with both Orders and Products table. If I place an order with 3 products, the OrderProductDetails datasheet would be:
On my report, instead of 3 entries for this order, I would like show just one entry under a column "Products Ordered" ---> Product 1, Product 2, Product 3.
I tried the Concatenate macros I found online, however, I am unable to configure them properly to use for this purpose.
I have a list (listA) which has a record source of a query object (queryA). The form (formA) which has listA in it, also has a text box for some of the fields requested in queryA. The goal is to provide a flexible filter for the records in the list, so the user can just type in 'K' in text box filter_name, and they will only see records matching the entry.
N0w, the scene is set! I can easily go into the query object, and in criteria type something like this:
Like "*" & [Forms]![formA]![filter_name] & "*"
This works! It flexible filters out the records matching the text box value.. But, if the record has NULL for the name, then it won't even match "**", which is the minimum criteria. So therefore I get exclusion of records, which I dont want.
So I thought perhaps there might be some control structure I can use in expressions... some if, else, end if statement? Does anyone know how to do this?
Alternatively I thought, I could write a function like this..
Function criteria(ByVal val As Variant) As Variant If (IsNull(val) Or IsEmpty(val) Or val = "") Then 'do nothing Else criteria = "Like *" & val & "*" End If End Function
And then in the queryA object for criteria you just use:
=criteria(Forms!formA!filter_name)
But this doesn't seem to work.. and I dont know how to debug this...
Any ideas? I thought the function was a neat solution, but it seems not!
Alright, I've got all the pieces to this puzzle, I just can't fit them together properly. I have two tables, tblTickets and tblTicketNotes. They are in a one-to-many relationship, there can be multiple Notes attached to a single ticket. I am trying to set up a query that will pull the first (earliest by date) note for each individual Ticket. Here are the fields from each table that would be of concern here:
tbTickets TicketID - Autonumber - Primary Key Issue - Text - I will be using this later as a criteria to limit with, but not neccessary
tblTicketNotes NoteID - Autonumber - Primary Key TicketID - Long Integer - This is the foreign key of the relationship DateStamp - Date/Time - This is the Note Date, I only want the first (earliest date) one Content - Memo -This is the note information I want
So all I want is the Content of the first/earliest Note for each individual Ticket. I know this should be fairly easy, but I am at a loss.
I have quite a large select query that pulls in Date values from different tables. The end result is a list of records, where each record has 7 types of dates, put in columns A, B, C, D, E, F, G. What I need to do is, for each record to compare dates in those columns and put the LATEST one of them in the column MDATE.
I've tried using IIF function, but it grows exponentially with the number of values involved, and it can only handle 5 values before its cause error "too large". Alternatively I thought I could write a function to return the max date and call it from within the query, something along the lines of "select *, fnMaxDate(A, B, C, D, E, F, G) as MDATE from tblBLAH etc". The function is:
---------------------- Public Function fnMaxDate(a As Date, b As Date, c As Date, d As Date, e As Date, f As Date, g As Date) As Date
Dim Temp As Date Temp = Nz(a, "01/01/1901")
If Nz(b, "01/01/1901") > Temp Then Temp = b If Nz(c, "01/01/1901") > Temp Then Temp = c If Nz(d, "01/01/1901") > Temp Then Temp = d If Nz(e, "01/01/1901") > Temp Then Temp = e If Nz(f, "01/01/1901") > Temp Then Temp = f If Nz(g, "01/01/1901") > Temp Then Temp = g
fnMaxDate = Temp
End Function ----------------------
I've put a break at the start of the function, to see what it'll come up with but when running the query it didn't appear to call it. All values in MDATE where #error.
Can someone advise me, please, on the best way of picking the LATEST date? I'd also appreciate it if you tell me why the function didn't get called, as I was quite certain it is possible to call user defined functions from within the query.
I have to join multiple values into a string for summarizing data on reports and exports. This process in vba is taking up to 10 minutes to process and will get worse as the size of these reports grow.
My method so far is to query the individual items into a recordset, loop through the values, adding them to the string then return the string in the query.
Here is an example:
Public Function SO_Description(intSO As Integer) As String Dim db As DAO.Database Dim rs As DAO.Recordset Dim strSQLSelect As String SO_Description = "Profiles: " Set db = CurrentDb
I've been toiling with the issue of WHERE clauses on the "Right" side of Left Joins. I'm aware that you need to use JOIN ON......AND.... rather than JOIN ON....WHERE.... if the WHERE relates to the Right Hand table.
I've even got an example in my DB where the above works, but now am struggling to use the same theory for other tables. Therefore, I went and created two Mickey Mouse tables to test the logic but am getting an error.
I have Table 1 with one field called Field 1 - values A, B, C Table 2 as follows
Field 1.....Field 2.......Field 3 A.............100 C.............200..........XXX
I hoped to have a query that finds all records on Table 1 and records on Table 2 where Field 1 matches on the two tables and Field3 = XXX
My SQL is SELECT Table1.Field1, Table2.Field1, Table2.Field2, Table2.Field3 FROM Table1 INNER JOIN Table2 ON Table1.Field1 = Table2.Field1 AND Table2.Field3="XXX";
And then called this join as a symbol or variable, and then have it use to select the items from these joined tables, can this be done in Access? Here is an example of a code that I created, but it has an error message saying the FROM syntax is incorrect.
Code: SELECT firstJOIN.trainID, firstJOIN.trainName, firstJOIN.stationID, firstJOIN.stationName, firstJOIN.distance_miles, firstJOIN.time_mins FROM (trains INNER JOIN ((station INNER JOIN lineStation ON station.stationID = lineStation.stationID) INNER JOIN bookingLeg ON bookingLeg.startID = station.stationID or bookingLeg.endID = station.stationID ) ON trains.trainID = bookingLeg.tid) as firstJOIN
Can Access do something similar to this, in the FROM statement I joined 4 tables, because each unique fields are in each table and I have to joined them to get those fields. I called this join firstJOIN and in the SELECT statement, I list those columns in the table by calling it firstJOIN.trainID. Can Access do something like this, but syntax it differently?
[1] AvailableCars consists of fields as Zone (eg. ZoneA, ZoneB, ZoneC) , CarCategory (eg. CarAA1, CarAB1, CarAA2 ... and so on), DailyRates, and Valid DateBounds (FromDate, ToDate).
[2] CarPics consists of CarCategory and Carpicture (Path of the car image).
Now I want to Bring Only those cars from the AvailableCars table and CarPics which satisfy the criteria of falling between Valid Date Bounds...I am using join as the following :
SELECT AVAILABLECARS.ZONE, AVAILABLECARS.CARCATEGORY, AVAILABLECARS.DAILYRATES, AVAILABLECARS.FROMDATE, AVAILABLECARS.TODATE, CARPICS.CARPICTURE FROM CARPICS JOIN AVAILABLECARS.CARCATEGORY = CARPICS.CARCATEGORY WHERE AVAILABLECARS.ZONECODE = "ZONEA2XY" AND AVAILABLECARS.FROMDATE BETWEEN "DATEVAR1" AND "DATEVAR2" ORDERBY AVAILABLECARS.ZONE, AVAILABLECARS.CARCATEGORY
Using above query, I am not able to get the desired results. :o
Can Any body help me in solving this problem ? :confused:
I need to write a query which retrieves all the records from first table and those matching from second table and also satisfies a criteria.
I had
Table 1 F1 F2 F3
Table 2 F4 F5 F6 F7
I had to get all the records from Table1 and also those matching with Table2 So i did left join and getting all the records. And I also need to check whether F3 in Table1 is in between F6 and F7 of Table2.
So I wrote query like this
SELECT Table1.F1, Table1.F2, Table2.F5 FROM Table1 LEFT JOIN Table2 ON (Table1.F1 = Table2.F4) WHERE Table1.F3 BETWEEN Table2.F6 AND Table2.F7;
I am getting only those records which are matching where condition. I need to get all the records including which match the criteria and also those which don't match.
I am trying to create a query which shows only the newest note for every prospect. I have the code below, but I get a 'Syntax error in JOIN Operation' when I try to run the query and TBLNotes is highlighted.
SELECT TBLProspect.CompanyName,TBLNotes.Note, TBLNotes.NoteDate FROM TBLNotes AS a INNER JOIN TBLProspect ON TBLProspect.LeadID=TBLNotes.LeadID WHERE ((((Select Count(*) from tblNotes where LeadID=a.LeadID and NoteDate>=a.NoteDate)) In (1))) ORDER BY a.LeadID, a.NoteDate DESC;
I hope someone out there can help me, I'm not an SQL experianced person, I only know enough to make problems. Anyway I believe my problem below is probably simple to someone that knows SQL very good. I have a link to a sample Access database if anyone is interested in helping me solve this.
The Sample Database (http://shadesoffire.net/files/db1.mdb)
Have a problem and can't quite seem to get it solved. I have simplified the whole thing to make it easier to understand.
I want a report that shows me the Product Category and Sum from work orders that were > $100.
I'm not quite sure how to do this, I've tried several methods of Joining and Sub queries but nothing really works. All I get in my results is product categories > 100. See I would expect the product category to be on the report even it it were $55 if it came from a work order containing total costs > 100.
I have manually supplied the results that I want, any help would be greatly appreciated. My real problem deals with larger results and numbers but these are the basics.
Linked is an Access database with one of my queries that show all work orders > 100. I would expect all those product categories in my summary report.
Redesign of the database is not an option.
These work orders are all > 100, the total on all reports should be $511
WorkOrderNo Total Cost 00001 $120.00 00003 $268.00 00005 $123.00
These product categories are associated with the above work orders and this is the result I am looking for.
Hi all, this is my first post to the board. I’ve been searching through the forums but haven’t been able to put all the pieces together on my problem. First some background on my application: I have 3 tables ISSUES, UPDATES, and PRTS. Each record in ISSUES has several records in UPDATES, and may have a single record in PRTS. The issues and updates tables have 3 “clones” (everything except the table name prefix is the same) that are used by other departments. All of the clones use the same PRTS table. I am trying to put a query into SQL (I first built it using the query builder & an example from Microsoft for a query to find the last record) that will return each issue, along with the last update associated with the issue. My intent is to switch the table names using code depending on the user’s selection. I know how to switch “ElectricISSUES” to “PowerISSUES” below, but I do not know how to switch the source for the “qryLastUpdate”. Any help would be greatly appreciated.
issueSQL = "SELECT ElectricISSUES.Index, ElectricISSUES.Status, ElectricISSUES.Description, ElectricISSUES.Driver, ElectricISSUES.Champion, ElectricISSUES.PRTS, ElectricISSUES.SubDate, ElectricISSUES.DateClosed, ElectricISSUES.Diamond, Date()-[Subdate] AS DaysOld, qryLastUpdate.Update, qryLastUpdate.Udate, qryPRTS.Step, qryPRTS.[Next Step], qryPRTS.Designee, qryPRTS.[Ewo#], qryPRTS.BreakPointDate " & _ "FROM (qryLastUpdate RIGHT JOIN ElectricISSUES ON qryLastUpdate.UIndex = ElectricISSUES.Index) LEFT JOIN qryPRTS ON ElectricISSUES.PRTS = qryPRTS.[Prob#] " & _ "WHERE (((ElectricISSUES.Status) = 'closed')) ORDER BY ElectricISSUES.Index;" db.OpenRecordset (issueSQL)
Hi all How are you? I have a small question.... I have a db with 2 tables (Contacts, Products). Contacts table has 6 columns (CustomerID, CustomerName, Bread, Tea, CD, Pencil) Products table has 2 columns (ProductID, ProductName). I want a query that show this result: Customer NameProduct Name JohnTea JohnCD MarkBread MarkCD MarkPencil JaneTea TonyBread TonyPencil
How can I do that?? Kindly, find attached the data base. Sorry for bothering you.