Problem:
I originally had a query that was working great but I'm now having to change it to pull more fields. When I try run the new query it picks a field name and says that I haven't included it as part of the aggregate function. Each time I get this error I can add the field the error specifies to the Group By statement and the error message will choose a new field that isn't included. Anyone have any idea's as to how I can get the same information I was getting with the original query just with more fields?
Description of how query is supposed to work:
The query is meant to pull one record for each distinct set of readings_miu_ids and ReadDates (The PremID field is the same for each distinct readings_miu_id).
Original Query:
strSql3 = " SELECT Distinct readings_miu_id, ReadDate, PremID " & _
"INTO analyzedCopy2 " & _
"FROM analyzedCopy "
DoCmd.SetWarnings False
DoCmd.RunSQL strSql3
DoCmd.SetWarnings True
New Query:
strSql3 = " SELECT Top 1 readings_miu_id, Reading, ReadDate,Format([MIUtime],'hh:mm:ss') AS ReadTime,MIUwindow,SN,Noise,RSSI,ColRSSI,MIURSSI,Firmware,CFGDate,FreqCorr,Active,MeterType,OriginCol,ColID,Ownage,SiteID,PremID , Neptune_prem.prem_group1, Neptune_prem.prem_group2,ReadID " & _
"INTO analyzedCopy2 " & _
"FROM analyzedCopy " & _
"Group By readings_miu_id, ReadDate, PremID " & _
"Order By readings_miu_id, ReadDate, ReadID, PremID "
DoCmd.SetWarnings False
DoCmd.RunSQL strSql3
DoCmd.SetWarnings True
In my experience (which is only moderate) every column in the result set (but NOT every aggregate) must be in the group by.
Here's a decent reference
When you include a GROUP BY clause, each field must either be in the GROUP BY or have an aggregate function (e.g, MAX, MIN, SUM, COUNT) applied to it.
For example, a simple correct implementation might be:
SELECT Department, MAX( Salary ) FROM Employees GROUP BY Department
... and a simple incorrect implementation would be:
SELECT Department, Salary FROM Employees GROUP BY Department.
Consider the two statements above. For the first, you can easily imagine what a datasource would look like and what would be returned. However for the second, what would you return? Which individual value of Salary would you return in your resultset? Hence, when you group fields, each field in the result set must either participate in the GROUPing or be the result of an aggregation of the values collected from the group comprised of the other fields.
You can accomplish this via a subquery or two queries. Also, "CurrentDb.Execute" is the preferred method to run a query like this (instead of "DoCmd.RunSQL").
CurrentDb.Execute strSQL3, dbFailOnError
Related
I want to use the result of a crosstab with a flexible amount of column headings in a form. The query shows how many hours employees (column headings) spent on different tasks (row headings).
The query works if I open it as is. Pulling it into the form I get the error message that I cannot use a crosstab query without fixed column headings. I need the ability to show a flexible amount of column headings since otherwise the resulting table is too big and confusing. Is there a solution for this problem?
That's the query:
PARAMETERS [Forms]![PL_Stundenabfrage]![ProjektWaehler] Long;
TRANSFORM Round(Sum(DateDiff("n",[tblZeiten].[ZE_Start],[tblZeiten].[ZE_Ende])/60),2) AS Stunden
SELECT [KS_Bez] & " (" & [KS_BezLang] & ")" AS Taetigkeit, Sum(Stunden) AS GESAMT
FROM tblMa INNER JOIN (tblKst INNER JOIN (tblPr INNER JOIN tblZeiten ON tblPr.PR_Key = tblZeiten.ZE_Pr) ON tblKst.KS_Key = tblZeiten.ZE_Kst) ON tblMa.MA_ISN = tblZeiten.ZE_MA
WHERE (((tblZeiten.ZE_Pr)=[Forms]![PL_Stundenabfrage]![ProjektWaehler]))
GROUP BY [KS_Bez] & " (" & [KS_BezLang] & ")"
PIVOT tblMa.MA_Nachname;
I am working on converting a legacy MS access system to a spring-boot application and I came across a big query. I am mostly done with converting the functions from access to mysql but not able to understand how to convert the following DLookUp sub-query as a mySql subquery
DLookUp("[price]","tbl_so","[so_id] = " & tbl_trade.so_id & " AND [product_id] = " & tbl_po.product_id
What I understood is following won't work as I don't have the Inner Joins set between the 3 tables, tbl_so, tbl_po, tbl_trade
SELECT tbl_so.price FROM tbl_so WHERE tbl_so.so_id = tbl_trade.so_id AND tbl_so.product_id = tbl_po.product_id
My question is how do I know how the tables will join with each other in this case and also when this DLookUp query is seldom used. And also the solution for this query.
Well, as a general rule, dlookup() can be replaced with a left join. However, you can also use a sub-query and they tend to be "less" change to the query.
So, if we had this:
SELECT id, partNum, dlookup("PartDescrt","tblParts","PartID = " & partNum)
as Description from tblOrders.
You would replace the above dlookup() with a sub-query like this:
SELECT id, partNum,
(select PartDescrt from tblParts where tblParts.PartID = tblOrders.PartNum)
AS Description
from tblOrders
The above is SQL or access sql syntax, but quite sure the same should work for MySQL.
If there is more then one partNumber that matches the above, then add a TOP 1, and a order by with some unique row (PK ID column is best). So the query becomes:
(select TOP 1 PartDescrt from tblParts where tblParts.PartID = tblOrders.PartNum
ORDER BY PartDescrt, ID DESC)
AS Description
i have a table like this and now my task is to fill the empty field with respect to vol and country of the respective column
rule : i have to see the highest volume in the vol field and take the country of that vol and put it in the empty field (ie i have to fill empty cell with country JP because the vol of japan is more )
like this i have to fill .
the remaining fileds like RB , Plant, MCR are changing for remaining empty cells.
i had use Dlookup for this but i coudnt get the solution could any one please help me it is very helpful if you find me the solution.
like this i have to fill all empty line in the table
Ok i am giving more clear view of my table view so that you can understand easily
this is the only table i have to do the task
and now my task is i have to fill the empty cells in the country field but the condition is i should look the RB , Plant ,MCM with respect to vol field (ie: if you see the table the RB , plant ,MCM feilds are same but the country and vol are changing for one group so i have to also consider the fields, that means if the RB, plant, mcm fields are same then i have to take the one of the country in the group with the highest volume) (i just give example in the first thre rows RB , plant , MCM are same so i have to take the highest volume country ie IN so the empty cell should be IN and secodn group empty cells should be TH like that i have to fill.
As I mentioned in my comment to Johnny Bones' answer, your original requirement could have been accomplished with an UPDATE statement that used the DLookup() and DMax() functions like this:
UPDATE MyTable
SET Country=DLookup("Country","MyTable","Vol=" & DMax("Vol","MyTable"))
WHERE Country IS NULL
Even with your revised requirements it is still possible, just more scary-looking:
UPDATE MyTable
SET Country=DLookup("Country","MyTable","RB='" & RB & "' AND Plant='" & Plant & "' AND MCM='" & MCM & "' AND Country IS NOT NULL AND Vol=" & Nz(DMax("Vol","MyTable","RB='" & RB & "' AND Plant='" & Plant & "' AND MCM='" & MCM & "' AND Country IS NOT NULL"),0))
WHERE Country IS NULL
The above query was tested and verified as working in Access 2010.
You can do it in VBA, and have more control over how it reacts. Something like this will do:
Dim db As Database
Dim rec As Recordset
Dim MySQL As String
Set db = CurrentDb
Set rec = db.OpenRecordset("Select Top 1 MyTable.Country FROM MyTable ORDER BY MyTable.Vol DESC")
MyCountry = rec(0)
rec.Close
SetWarnings = False
MySQL = "UPDATE MyTable SET MyTable.Country = '" & MyCountry & "' WHERE IsNull(MyTable.Country) or Len(MyTable.Country) < 2"
DoCmd.RunSQL MySQL
SetWarnings = True
db.Close
I tested the above and it works, although if your table's field's properties are different you may need to tweak some of the code.
Obviously, anywhere you see "MyTable" you should use your own table's name.
I'm trying to return records for an alert system based on two conditions.
The first condition is there is a booking in the system for tomorrow's date [Date()+1] with a Type value of B. If that JobNumber also has a Type value (in another record) of A AND the Result field's value is "Not Approved" we need to return an alert.
Example table:
JobNumber Type Company Date Result
58129 B 3 22/03/2013
58129 A 3 20/03/2013 Not Approved
58129 C 3
So far I have been able to create a SQL query in VBA to return the results of the first condition and have looped through the results to return the relevant JobNumbers. How do I insert these JobNumbers as criteria for the second SQL query or is it possible to combine all criteria into one SQL statement?
My SQL so far:
strSQL1 = "SELECT I.JobNumber, I.Type, I.Company, I.Date, I.Result " & _
"FROM tblInspection I " & _
"WHERE (((I.Type)='B') AND ((I.Date)=Date()+1));"
strSQL2 = "SELECT I.JobNumber, I.Type, I.Company, I.Date, I.Result " & _
"FROM tblInspection I " & _
"WHERE (((I.Type)='A') AND ((I.Result)<>'approved'));"
Any help would be much appreciated.
You can get a field from the same or another table. This will give an error if more than one row is returned, but whether or not more than one row will be returned depends on your data. If it is likely, you will need to add another criterion, such as date.
SELECT I.JobNumber, I.Type, I.Company, I.Date, I.Result,
(SELECT Result
FROM tblInspection q
WHERE q.JobNumber=i.JobNumber
AND Result="Not Approved"
AND Type="A")
As ResultA
FROM tblInspection I
WHERE I.Type='B' AND I.Date=Date()+1
How do I ensure that I pick up the right number of records when filtering for dates within an Access Query:
SELECT ID, REF, SalesDate, DCount("ID","tblRecords"," Ref='" & [Ref] & "' AND [SalesDate]=#" & format([SalesDate],"yyyy/mm/dd") & "#") as EXPR1 from tblCurrent
It picks up the date ok if it cannot be misconstrued such as 28-04-12, but if it is 04-06-12 it doesn't pick it up as it's assuming it's the wrong way around.
Note that this query is not created on the fly or generated from a form etc...
I either use yyyy/mm/dd for dates in VBA:
#" & Format([SalesDate],"yyyy/mm/dd") & "#"
Or parameters, for building queries.
EDIT re additional information
Seeing you are using SQL server, I suggest you use a derived table, which you may find faster, for example:
SELECT dbo_Table_1.ADate, ACount FROM dbo_Table_1
LEFT JOIN (SELECT a.ADate,Count(*) As ACount
FROM dbo_Table_1 As a GROUP BY a.ADate) b
ON dbo_Table_1.Adate=b.ADate
EDIT re discussion
SELECT * FROM dbo_vwRecordsCurrent As t
LEFT JOIN (
SELECT a.OpptyIncentiveModifiedDate, a.DataSetID, Count(*) AS ACount
FROM dbo_vwRecordsHistorical AS a
WHERE a.OpportunityIgnored = True
GROUP BY a.OpptyIncentiveModifiedDate, a.DataSetID) AS h
ON t.OpptyIncentiveModifiedDate = h.OpptyIncentiveModifiedDate
AND t.DataSetID = h.DataSetID
I have aliased your tables as the names are very long, so to me, it is more readable to use aliases on the outer sql. They are essential in the inner sql. It is not a good idea to alias a derived table with the name of an existing table.