count and remove duplicate access vba - ms-access

Here is some code I have to remove duplicate occurances of catid & recid in tblcat1_rec table, leaving only 1 entry:
mysql = "DELETE FROM tblcat1_rec "
mysql = mysql & " WHERE ID <> (SELECT Min(ID) AS MinOfID FROM tblcat1_rec AS Dupe "
mysql = mysql & " WHERE (Dupe.catid = tblcat1_rec.catid) "
mysql = mysql & " AND (Dupe.recid = tblcat1_rec.recid)); "
DoCmd.RunSQL mysql
I'd like for a count of the total amount of total duplicates found to be put into the "TL" column of the record that remains. Which would also mean, a value of 1 for records that are allready unique.

I think you will have to break this down into two parts. Firstly put the count of all the records for each catid & recid and then take 1 off. After that you can run the delete SQL statement you have here.

Related

Regarding fill some empty fields in access table

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.

How can I find records in a table / recordset based on the result of a query on the same table?

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

asp + msaccess , compare keywords in a table

Hopefully someone has done this so has a bit of code which may help me
I currently have this query
ForumID = request("ID")
QID = ForumID
DB.CreateQueryDef QID, "SELECT * FROM Topic WHERE Keywords = '" & QID & "' ORDER BY LastPost DESC"
What I have is a table topic which contains the topics. I have added a field keywords, which will have keywords eg "motocross, mx, motox"
How can i query the database eg any table which contains the keyword motocross?
Also how can this use multiple words
eg
two topics
topic1 -> Keywords motocross, mx
topic2 -> Keywords motocross, dance
if eg search.asp?ID= motocross unrelated
it will search database for both, eg get all topics where keywords field contain eith of the 2 words in query, or 4 words or more
Also is it possible to do relavent search like youtubes like this?
two topics
topic1 -> Keywords motocross, 1
topic2 -> Keywords motocross, 2
eg search.asp?ID=motocross 1
topic 1 will show first as both words in query match "motocross" and "1" whereas topic2 only has motocross
is it possible to do this so it will count keyword matches
have you tried using LIKE ??
"select * from table where field LIKE '%" & value & "%'"
First of all, your querystring should not contain spaces. Use a different delimiter. A + is a good one to use. So your URL will look like: search.asp?ID=motocross+1 instead.
This will split your kewwords into an array, then take them one at a time to build the and clause. The replace removes the first AND.
SQL = "SELECT * FROM Topic WHERE"
ForumID = request("ID")
QID = Split(ForumID, "+")
For Each KW in QID
SQL = SQL & "AND Keywords Like '*" & QID & "*' "
Next
SQL = Replace(SQl, "WHEREAND", "WHERE")
SQL = SQL & " ORDER BY LastPost DESC"
you need to make your Query with "OR" ....
I have 2 keyword(car , Bus) so my query will be like
DB.CreateQueryDef QID, "SELECT * FROM Topic WHERE (Keywords = 'car' OR Keywords = 'Bus') ORDER BY LastPost DESC"
this is just example as static query you can make it run time with loop of your comma separated values..

Open Form in Access from Cross Table Query

Here is the scenario. I have a database that is single function basically to manage documents. There are two tables that I am dealing with for this example.
Table 1: Table of Documents with the following fields DOCUMENT_NUM, PK; DOCUMENT_NAME; etc. One-to-many relationship to Table 1 with referential integrity based on DOCUMENT_NUM
Table 2: Table of revision history of documents with fields DOCUMENT_NUM, PK; REVISION_DATE; REVISION_NUM.
I have a form that enters in the information for Table 1, and another form that enters in information into Table 2 pulling in DOCUMENT_NUM off the criteria in Form 1.
My problem: I have a search form that I want to be able to open Form 1 that is bound to Table 1 by searching for not only parameters that are in Table 1 but also in Table 2. Example: Search for documents revised between ##/##/#### and ##/##/#### but will open Form 1 with the "DOCUMENT_NUM", "DOCUMENT_NAME", etc. However I cannot do the search since From 1 is bound to Table 1 and the information I am querying against is in Table 2.
The Search uses DoCmd.OpenForm "Documents",,,strQuery where strQuery = "1=1 AND [SOPS].[SOP_NUMBER] = 'QA-001' AND [SOP_REVISIONS].[REVISION_DATE] >= #12/02/2011# AND [SOP_REVISIONS].[REVISION_DATE] <= #12/02/2012#"
([SOPS] == Table 1 && [SOP_REVISIONS] == Table 2)
How about:
strQuery = "1=1 AND [SOPS].[SOP_NUMBER] = 'QA-001' " _
& "AND DOCUMENT_NUM IN (" _
& " SELECT DOCUMENT_NUM FROM [SOP_REVISIONS] " _
& " WHERE [SOP_REVISIONS].[REVISION_DATE] >= #12/02/2011# " _
& " AND [SOP_REVISIONS].[REVISION_DATE] <= #12/02/2012#)"
In other words, use a subquery to get the related DOCUMENT_NUM from [SOP_REVISIONS].

Why is my query demanding more fields in my Group By?

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