Queries :: At Most One Record Can Be Returned By Subquery - Error 3354
Sep 1, 2013
At most one record can be returned by this subquery. (Error 3354)
This is my SQL:
SELECT Students.[Student ID], Students.[Student Name]
FROM Students
WHERE (((Students.[Student ID])=(SELECT [Student ID]
FROM [Student_Sports]
WHERE [Sporting Team] = [Forms]![SV_Teams]![txtTeam])));
I have a subquery on a table which got the previous and next rows from a table. This worked fine, until I started replacing my table with real data instead of dummy-data. I now receive the "at most one record can be returned by subquery" error every time I run it. I checked that I do not have any identical rows.
My query:
Code: SELECT z.DateFrom, z.DateTo, z.ArticleID, z.retailerID, z.Actuals, z.Statistical, (SELECT y.Actuals FROM tblActuals AS y WHERE (y.retailerID=z.retailerID) AND (y.ArticleID=z.ArticleID) AND ((DatePart("ww",z.DateFrom,2,3)-1)=DatePart("ww",y.DateFrom,2,3))) AS ActualsMin1 FROM tblActuals AS z;
I append new rows via a VBA-script from another table.
I wrote a query to return the TOP 32 items for a key. Works fine:-
SELECT TOP 32 [my Disks Coefficients sub].[thier Disk ID] FROM [my Disks Coefficients] AS [my Disks Coefficients sub] WHERE [my Disks Coefficients sub].[my Disk ID]=1 GROUP BY [my Disks Coefficients sub].[thier Disk ID], [my Disks Coefficients sub].coefficient ORDER BY [my Disks Coefficients sub].coefficient;
I then plugged this into a query in the WHERE clause using In (Select Top .....;); [changing the =1 condition to pick up the correct id from the emcompassing query]:-
SELECT [my Disks Coefficients].[my Disk ID], [my Disks Coefficients].[thier Disk ID], [my Disks Coefficients].coefficient FROM [my Disks Coefficients] WHERE [my Disks Coefficients].[thier Disk ID] In (SELECT TOP 32 [my Disks Coefficients sub].[thier Disk ID] FROM [my Disks Coefficients] AS [my Disks Coefficients sub] WHERE [my Disks Coefficients sub].[my Disk ID]=[my Disks Coefficients].[my Disk ID] GROUP BY [my Disks Coefficients sub].[thier Disk ID], [my Disks Coefficients sub].coefficient ORDER BY [my Disks Coefficients sub].coefficient;);
This runs fine but the the number of items returned is for each key is less than if I run the Top query by itself for each key seperately? So when I run it stand-alone for ID 1 I get 127 rows (there are many equal coefficients); when I run it as a sub-query I get only 121 rows for ID 1!
We are developing a complaints tool. Each completed complaint needs to be signed off by 3 leads and I'm hoping to display the progress of this in a form. Obtaining the first is simple and I was able to do that relatively quickly. The subsequence ones are now giving me a headache as it doesn't seem I can reference the initial subquery field in the others.Here's what I have so far:
Code: SELECT COMPLAINT_TBL.COMPLAINTID, COMPLAINT_TBL.CASENUMBER, COMPLAINT_TBL.COMPLAINTANTFORENAME, COMPLAINT_TBL.COMPLAINTANTSURNAME, BUSINESSUNIT_TBL.BUSINESSUNIT, COMPLAINT_TBL.FINALRESPONSEDATE, (SELECT TOP 1 [SIGNOFF_TBL].[SIGNOFFDATE] FROM [SIGNOFF_TBL] WHERE [SIGNOFF_TBL].[COMPLAINTID] = COMPLAINT_TBL.COMPLAINTID ORDER BY [SIGNOFF_TBL].[SIGNOFFDATE] DESC) AS FIRSTSIGNOFF,
I have a query that returns several records, typically 1 to 5. I need to print a label for each record returned by the query. Printing a label is no problem, but how do I print sequentally for each record in the query?
I have a table of accounts and a table of rates. There is a one-to-many relationship between them (i.e. each account can have multiple rates, each with their own - unique - effective date)
I'm trying to build a query which will show me all of the accounts in the accounts table and the most recent rate (based on the effective date) for each of those accounts.
This is as far as I've gotten with the SQL :
Code: SELECT [tblAccounts].[AccountID], [tblAccounts].[AccountNumber], [tblAccounts].[AccountName], [LatestRate].[IntRate], [LatestRate].[EffectiveDate] FROM [tblAccounts] LEFT JOIN (SELECT TOP 1 [tblRates].[AccountID], [tblRates].[IntRate], [tblRates].[EffectiveDate] FROM [tblRates] ORDER BY [tblRates].[EffectiveDate] DESC) AS LatestRate ON [tblAccounts].[AccountID] = [LatestRate].[AccountID]
But this can't work because the [LatestRate] subquery can only ever return one record (i.e. the most recent rate across all of the accounts)
I need the most recent rate for each of the accounts in the main query
(FYI - I use an outer join as it is possible for no rate to be available in the rates table for a given account, in which case I want to return the null value rather than omit the account from the resulting dataset...)
Finally got my DB straight so I am not using calculated fields however can't figure out the best way to handle the Combo Box so I do not show closed records ( Item checked out and item returned).
Please see the attached table of materials checked out and materials returned. How to setup a query so that if an item has been returned and matches the item checked out, Both the original check-in and the matching return records are filtered and not displayed in the Combo Box.
Also, I am a little worried about partial returns as when an employee only returns half the amount.
Extended Cost] and salestran.[Extended Price] for each salestran.[SKU Code/Number], Count the number of unique customers, salestran.[Customer Code/Number], per SKU for any transactions equal to or after salestran.[Transaction Date] 11/1/2014.
Problem is, doing a regular count on the Customer field returns an incorrect value. It counts the number of times the sku appears within the given date range, ie 6 transactions with 2 customers, my count says 6. I need a distinct count on the customer, for the above example I want to see 2. Here is the code I have so far which yields an error of "At most one record can be returned.." distinct count in my Select statement along with the other fields I want to see, ie Summary data and SKU.
SELECT Salestran.[SKU Code/Number], (SELECT COUNT(cd.[Customer Code/Number]) AS Count FROM (SELECT Distinct [SKU Code/Number], [Customer Code/Number] FROM Salestran) as cd GROUP BY cd.[SKU Code/Number]) AS [Number of Customers] FROM Salestran WHERE (((Salestran.[Transaction Date])>=#11/1/2014#)) GROUP BY Salestran.[SKU Code/Number];
I need to select a record with the latest (max) date along with associated values that go along with that record. However, some records have the same date. Initial query sorts by Asset_ID and Date (Desc)...A second query against the initial query then groups by Asset_ID, taking the Max Date and First Switch and Port...Results show the latest date but with a different Switch and Port
Good afternoon! I have a database that tracks the withdraws and returns of shared tools. The withdraw form has a check box on it that is checked to show removed when the item is ordered (this keeps that item from showing up in inventory searches). When the item is returned, that check box is unchecked, showing that the item can be withdrawn again.
When a person withdraws an item their supervisors name is also logged so that we know who to chase down when the item doesn't come back.
I have a query that is supposed to show what items are still outstanding based on a date range (I got the prompt for date range to work..yea me). However, the query shows every time that the item was borrowed.
Example... I borrow a hammer and my supervisor is Bob. I return the hammer. It does not show as still withdrawn in my query.
The next I borrow the same hammer and again my supervisor is Bob. I return the hammer. It does not show as still withdrawn in my query.
The day after I borrow the same hammer and my supervisor is Joe. I return the hammer. It does not show as still withdrawn in my query.
Some other day I borrow the same hammer and my supervisor is Joe. I do not return the hammer. The two times I borrowed the hammer with my supervisor as Bob show up as well as the other time that I borrwed it with my supervisor as Joe shows up as well as the one that shows I still have it. . One of the criteria in the query is essentially only show the items that have the check box checked (criteria=true). But that apparently does nothing, or (more than likely), I am doing something wrong.
This is the SQL:
SELECT tblOrder.OrderDate, tblOrder.Supervisor, tblEmployee.EmployeeFirst, tblEmployee.EmployeeLast, tblItemSpecifics.Description, tblItemSpecifics.Serial_Number FROM (tblEmployee INNER JOIN tblOrder ON tblEmployee.GlobalID = tblOrder.GID) INNER JOIN (tblItemSpecifics INNER JOIN tblOrderInfo ON tblItemSpecifics.Serial_Number = tblOrderInfo.Serial_Number) ON tblOrder.OrderNumber = tblOrderInfo.Order_Number GROUP BY tblItemSpecifics.Removed, tblOrder.OrderDate, tblOrder.Supervisor, tblEmployee.EmployeeFirst, tblEmployee.EmployeeLast, tblItemSpecifics.Description, tblItemSpecifics.Serial_Number HAVING (((tblItemSpecifics.Removed)=True));
I'm doing a subquery to select the top 5 of products for each supplier. The selection needs to be done randomly on the products for each supplier. For this I have made the following query (based on Allen Browne's example):
SELECT tblProducts_temp.SupplierID, tblProducts_temp.GTIN FROM tblProducts_temp GROUP BY tblProducts_temp.SupplierID, tblProducts_temp.GTIN HAVING (((tblProducts_temp.GTIN) In (SELECT TOP 5 Dupe.GTIN FROM tblProducts_temp AS Dupe WHERE Dupe.SupplierID = tblProducts_temp.SupplierID ORDER BY RND(Dupe.GTIN) DESC))) ORDER BY tblProducts_temp.SupplierID, tblProducts_temp.GTIN;
The query returns a random number of products, but not a top 5. So for supplier X one time 3 products and the next time for supplier X 7 products.The query without the RND function, so just the top 5 works fine:
SELECT tblProducts_temp.SupplierID, tblProducts_temp.GTIN FROM tblProducts_temp GROUP BY tblProducts_temp.SupplierID, tblProducts_temp.GTIN HAVING (((tblProducts_temp.GTIN) In (SELECT TOP 5 Dupe.GTIN FROM tblProducts_temp AS Dupe WHERE Dupe.SupplierID = tblProducts_temp.SupplierID ORDER BY Dupe.GTIN DESC))) ORDER BY tblProducts_temp.SupplierID, tblProducts_temp.GTIN;
I have a one-to-many query which I would like to add a subquery to eliminate all but the TOP 1 of a field.
Here is the SQL:
Code: SELECT QrySitesBatteries.SiteKey, QrySitesBatteries.SITEID, QrySitesBatteries.Battery FROM QrySitesBatteries WHERE (((QrySitesBatteries.Battery)=[Forms]![FMHome]![Battery])) OR ((([Forms]![FMHome]![Battery]) Is Null)) ORDER BY QrySitesBatteries.SITEID;
And I would like to only show the TOP 1 of the SiteKey field.
So, I think I have to add the subquery before the ORDER BY, but how to do it?
I'm trying to run a line of code after doing a Query Search that reports back the total number of results pulled from the search. I've dug around and found some useful code, but nothing that gives the results I'm needing. Most everything gives me the total number from the query. I'm also using a Split Form.
The process goes: Enter numeric search in Text10 and hit the search button to run the following macro: [studentID]=[Forms]![Query1]![Text10]
It then gives me the requested information.I have a second text box (Text19) that needs to display the number of pulled results. I've written VBA that only gives me the total number searched for studentID or for the entire Query.
I have a race league, I want to select the top 10 point scores for each member.
I have read the Allen Browne article (and many others) and tried many variations on his code but cannot get this working.
I face two issues - The ORDER by clause has no effect, points are not sorted with largest first - Access being unable to differentiate between scores with the same value and returning additional records. I have added an "Event" field to make the record unique, but this does not seem to work.
Query code is
SELECT qLeague.Member, qLeague.Event, qLeague.Points FROM qLeague WHERE qLeague.Points IN (SELECT TOP 10 Points FROM qLeague AS Dupe WHERE Dupe.Points= qLeague.Points ORDER BY Dupe.Member, Dupe.Points DESC ) ORDER BY qLeague.Member ASC, qLeague.Points;
This returns more than 10 results per member:
Member Event Points Alex Peters SDMC North Weald Sprint 3 Alex Peters HCAAC Debden May 3 Alex Peters GB/Harrow TAMS NW Sprint 4 Alex Peters HCAAC Debden Sprint 5 Alex Peters Llys y Fran Hillclimb 6
I've created the following but it keeps coming up with the error message You tried to execute a query that does not include the specified expression 'ICE Team' as part of an aggregate function.
SELECT ztSub.[Master Sheet].[ICE Team], ztSub.[date], Count(ztSub.[Count]) FROM (SELECT [Master Sheet].[ICE Team],[Master Sheet].[Visit Date (planned for)] AS [date],Count([Master Sheet]![Visit Date (planned for)]) AS [Count] FROM [Master Sheet] UNION SELECT [Master Sheet].[ICE Team],[Master Sheet].[Date retasked to?] AS [date], Count ([Master Sheet]![Date retasked to?]) AS [Count] FROM [Master Sheet] ) AS ztSub GROUP BY ztSub.[Master Sheet].[ICE Team];
Can anyone tell me what is wrong with this complex query? It works fine without the highlighted subquery. The subquery works fine on its own. But they don't work together.
I think that I might not be able to call multiple results from a subquery but I'm not sure about that. Does any one know???
Any help will be much appreciated! Thanks! select k.site_id, s.name, t.date_opened,
(select concat(c.name_first,' ', c.name_last) as User from sitepack_approval sa left join sitepack_approval_users spa on sa.approval_id=spa.approval_id left join contacts c on spa.user_id=c.contact_id where sa.site_id=k.site_id and spa.timestamp is null order by spa.level limit 1) as pending_approver,
(select sat.name from sitepack_approval sa left join sitepack_approval_types sat on sa.approval_type_id=sat.approval_type_id where sa.site_id=k.site_id order by sa.approval_id desc limit 1) as sitepack_type,
(select t.site_id, D.name AS Division, R.name AS Region, M.name AS Market, concat(C1.name_first, " ",C1.name_last) AS RD, concat(C2.name_first," ",C2.name_last) AS DD FROM stores as t LEFT JOIN regions as M ON t.region_id = M.region_id LEFT JOIN regions AS R ON M.parent_region_id = R.region_id LEFT JOIN regions AS D ON R.parent_region_id = D.region_id LEFT JOIN contacts AS C1 ON R.contact_id = C1.contact_id LEFT JOIN contacts AS C2 ON D.contact_id = C2.contact_id) as site, Divsn, Reg, Mkt, RDs, DDs,
concat(cd.name_first,' ',cd.name_last) as 'DRE'
FROM sitepacks k LEFT JOIN sites s on k.site_id=s.site_id LEFT JOIN stores t on k.site_id=t.site_id LEFT JOIN contacts cd on k.dre_contact_id=cd.contact_id WHERE status_id=(select status_id from sitepack_status where description='Approving' and sitepack_type <> 'Renewal') and t.status_code <> 'DEAD' and t.date_opened > now();
I can get the number of records to be returned but I want to run a condition if the records returned is zero. To do this, I need to put the number returned into a variable but I haven't been find a way.
For instance, this code does work:
SQL = "SELECT Count(*) AS Records FROM Table1 GROUP BY Table1.Quantity HAVING (((Table1.Quantity)=4));" conDatabase.Execute SQL
But I want to store the count as a variable. What I want is something that look this (it doesn't work but I just want to give an idea what I'm looking for)
SQL = "SELECT Count(*) AS Records FROM Table1 GROUP BY Table1.Quantity HAVING (((Table1.Quantity)=4));" Dim hold as Integer hold = conDatabase.Execute SQL
If(hold = 0) Then 'tell them nothing returned End If
So how can I go about this?
Update: I see that someone posted a solution a few threads down using queries which did work. Can I still still do the same thing with SQL strings?
I have a query that i run and now I am adding another column to provide a ETA for an order, when i specify a date I only get results that have that date and when I leave out the date I get too many results. Can someone please let me know how I can modify my query so that I get all the results with an ETA and also all the accounts that do not have an order placed.
I am trying to create a Membership report that shows member activity over several months.
My problem is that the software that gives me the Member Activity does not report on accounts that were not used during that month and some members do not come in every month.
I have a Member's Details table as well as individual months activity and have queries set to show the results of each month individually (these work, obviously)
The Reports I am trying to get from Access only show the activity of Members that have some movement every month, but totally skips members that are not present for 1 or more.
The report uses these queries but fails to report any member that is not in the tables for all months.
Example:
September Rank Member FirstName LastName Activity 1 100 Andy Todd 200
October Rank Member FirstName LastName Activity
November Rank Member FirstName LastName Activity 5 100 Andy Todd 50
The report needs to show: Member FirstName LastName Sept.Rank Sept.Activity Oct.Rank Oct.Activity Nov.Rank Nov.Activity but will not because there are no values for that member in October.
I am teaching myself Access as I go, so I am sure there is an easy solution.
I have an Access database set up with a table, several queries and forms (Weekly, Monthly, Quarterly, Pending). When I click on the any of the forms the table come up with rows of data just like it should. When I click on any of the rows instead of the data coming up so that I can edit it the entire Access database shuts down and then restarts. A backup version of the database is generated and it asks me to save it. I have verified that the forms are linked to the correct queries so I'm at a loss as to why this is occurring.
Hello I have had a bit of a stumbling block with a subquery for a Daily production report and I was hoping someone could advise me.
An initial query presents the information as the table below.
Date ProdNoFirstOfSerialNoLastOfSerialNo Qty 13/11/2006004006P064600254P06460028128 13/11/2006004006P064600282P06460030019 13/11/2006004105P064600301P0646003033 13/11/2006004006P064600304P06460031714 13/11/2006004006P064600318P06460034427
However what I need to have is the table actually look like this,
Date ProdNoFirstOfSerialNoLastOfSerialNo Qty 13/11/2006004006P064600254P06460030047 13/11/2006004105P064600301P0646003033 13/11/2006004006P064600304P06460034441
I had thought to try and make another query identify the change of product number to then set the first and last serialNo's but I have no idea on how to write the statments necessary. If anyone could offer some advice it would be very much appreciated.
I haven't used subqueries before, so I am not 100% on the best way to approach this.
The Scenario:
I have tables;
tblJobDetails tblMissingKit tblSiteDeficiencies
JobID is the primary key for tblJobDetails. tblMissingKit and tblSiteDeficiencies are both tables containing (funnily enough) Missing Kit and Site Deficiences on the Job's (JobIDs) in tblJobDetails. The problem is, there can be more than 1 amount of missing Kit per JobID and more than 1 site deficiency per JobID.
In an ideal world, when I run this query, I would only get 1 record per JobID, but in a 'MissingKit' field, there would be a list of the missing kit for that site (new lines, comma seperated - doesn't matter) and then the same with Site Deficiencies.
Not sure if this is even doable, but thought I'd ask the people who know.
2) Can the parameter value be the value from another field in the query?
In a nutshell, I want to write a query that returns these fields about some marbles:
Color of Marble Marble Stat1 Marble Stat2 Marble Stat3 Number of Marbles of this Color
i.e. desired query results
Blue Stat1 Stat2 Stat3 24 Red Stat1 Stat2 Stat3 12 Green Stat1 Stat2 Stat3 38
The query is fine except for the last field, Number of Marbles of this Color. This field is a subquery with a parameter that is the color of the marble. So if I run the subquery on its own and pass 'blue' as the parameter, it returns 24.
Here is the SQL for the subquery, qry_Count_Marbles:
SELECT Count([Marble_ID]) AS [Count] FROM tbl_Marble_Info WHERE (((tbl_Marble_Info.COLOR)=[Marble_Color]));
Marble_Color is a parameter, and If I enter 'blue' it returns 24.
In my main query, I am trying to pass the parameter for the subquery as the result of the first field. It's not working, but here is my SQL:
SELECT tbl_Marble_Guidelines.COLOR, tbl_Marble_Guidelines.LOW, tbl_Marble_Guidelines.HIGH, tbl_Marble_Guidelines.FUND, qry_Count_Marbles.Count(tbl_Marble_Guidelines.COLO R) FROM tbl_Marble_Guidelines, qry_Count_Marbles
I'd like the main query to not prompt the user for the parameter, but simply grab the parameter value from the value of the first field. Is what I'm trying to do possible? Is there a way to pass a SQL parameter within the SQL itself, and not prompt the user?