Counting fields from related table WITH Where Statement - ms-access-2007

I would like to count fields from related table with WHERE Statement.
For counting data from related table I used this statement.
=DCount("ID","Customers","AddressID=" & AddressID)
I have to count customers for each address that customer is registred with WHERE statement where I will check how many customers are banned for each address.

You can build up the where statement like so:
=DCount("ID","Customers","Banned = False And AddressID=" & AddressID)
=DCount("ID","Customers","Banned = 'No' And AddressID=" & AddressID)
=DCount("ID","Customers","Banned = ""No"" And AddressID=" & AddressID)
=DCount("ID","Customers","DateBanned = #2012/09/21# And AddressID=" & AddressID)
The third argument of domain aggregate functions such as DCount is the where statement (criteria), and you can use most of the expressions that you would use in a query in that argument.

Related

Appending Data to SQL Server from Access Query Results in Error

I am appending data from an Access query into an existing table in SQL Server (2019) and sometimes NULL values cause a "Record is deleted" msgbox (no error number).
For instance, I have 3 columns (Text1, Text2, Text3) all are nvarchar(255) and Text1 accepts NULL values but sometimes Text2 doesn't... they are literally the same field with the same data. There is absolutely nothing different with the columns in SQL Server nor the fields in the query. This shouldn't be happening.
The other thing is that I made a make-table query off of the query and using that new table instead of the query caused no problems at all! Why is this? and how do I get the query to append data consistently?
I have tried append queries as well as straight up SQL in a DoCmd.RunSQL
The SqlSRV table is connected via custom ODBC string in Linked Table Manager.
From a query; this gives errors:
INSERT INTO tmakContact ( DataAsOf, ContactId, FullName, LoanNum, LoanId, Name, JobTitle, Email, Relationship, Company, Address, CityStateZip, [Number], PhoneNumType )
SELECT DataAsOf, ContactId, FullName, LoanNum, LoanId, Name, JobTitle, Email, Relationship, Company, Address, CityStateZip, [Number], PhoneNumType
FROM qryContact;
When I take out "Relationship" and "PhoneNumType" fields, the INSERT from this query works fine. These two fields come from outer joined tables. These tables are from another SQL Server and database I link to from within Access via custom ODBC string in Linked Table Manager.
From a table which I made in a make table query from qryContact gives no errors!
INSERT INTO tmakContact ( DataAsOf, ContactId, FullName, LoanNum, LoanId, Name, JobTitle, Email, Relationship, Company, Address, CityStateZip, [Number], PhoneNumType )
SELECT DataAsOf, ContactId, FullName, LoanNum, LoanId, Name, JobTitle, Email, Relationship, Company, Address, CityStateZip, [Number], PhoneNumType
FROM tmptblContact;
Originally I just ran DoCmd.OpenQuery "apdContact" which doesn’t work, which is just a saved append query using the same code as above.
SQL for qryContact:
SELECT Now() AS DataAsOf, dbo_Contact.Id AS ContactId, dbo_UserInfo.FullName, dbo_Loaninfo.LoanNum, dbo_ContactLoanLink.LoanId, dbo_Contact.Name, dbo_Contact.JobTitle, dbo_Email.Addr AS Email, Trim([dbo_ContactRelationship]![Descr]) AS Relationship, dbo_Contact.Company, [Add1] & " " & [Add2] AS Address, StrConv([City],3) & ", " & [StateCode] & " " & [Zip] AS CityStateZip, qryPhone.Number, qryPhone.PhoneNumType
FROM ((((dbo_Loaninfo INNER JOIN ((dbo_ContactLoanLink INNER JOIN dbo_Contact ON dbo_ContactLoanLink.ContactId = dbo_Contact.Id) LEFT JOIN dbo_Address ON dbo_Contact.BusAddrAId = dbo_Address.Id) ON dbo_Loaninfo.Id = dbo_ContactLoanLink.LoanId) LEFT JOIN dbo_ContactRelationship ON dbo_ContactLoanLink.ContactRelationshipId = dbo_ContactRelationship.Id) LEFT JOIN dbo_Email ON dbo_Contact.Id = dbo_Email.ContactId) LEFT JOIN qryPhone ON dbo_Contact.Id = qryPhone.ContactId) LEFT JOIN dbo_UserInfo ON dbo_Loaninfo.AssignedUserId = dbo_UserInfo.Id
WHERE (((dbo_Contact.InactiveFlag)="N") AND ((dbo_Loaninfo.LoanStatusId)<>1105) AND ((dbo_Loaninfo.InactiveFlag)="N") AND ((dbo_Loaninfo.PaidOffFlag)="N"));
Hum, does the table in question have any true/false columns - even if not used in your query? (a bit column in the table?).
Double, triple check that the target table in SQL server (no doublt a linked table to Access) has any bit columns, and if yes, MAKE SURE the column has a deafult value (0), for false.
Next up:
You don't mention if the target table in question has a autonumber PK column (I suspect it must have - but do check, and make sure that such a table has a PK).
next up:
Are their any real, or single/double columns in that target table - Again EVEN IF THEY ARE NOT part of your query, make sure such columns have a default setting in sql server (0).
last up:
Add a row version column to the sql server target table. That so called "row version" column in sql is named timestamp. (this is the worlds WORST name, since that timestamp column has ZERO to do with "time" or date or whatever. it is a ACTUAL row version system, and access supports this feature.
It also means that access will not do a column by column compare to the record when doing updates, or inserts. So, try adding a timestamp (aka: row version) column to the target table, and re-link from access.

Access or SQL: Need help returning data from a field whose field name is dynamically chosen in a query

I have a legacy database in SQL set up like a spreadsheet with 50 columns. Apart from employee names, the field names would be Machine01, Machine02, etc. and the records would include the date certified on each machine. I am using Access as a legacy front end because there is already so much already coded and staff trained with it.
How would I go about writing a query that would provide the dates each person is certified on, say, Machine27?
In Access, I initially had
SELECT LastName, FirstName, Forms![F: Reports Switchboard]![Machine Name] As Expr1
FROM Certifications
WHERE Forms![F: Reports Switchboard]![Machine Name]>""
But this provides a column filled with the machine name, not the dates in the field with that name.
I tried a number of other methods including a stored procedure:
CREATE PROCEDURE sp_CertDate
#fieldvar1 varchar(20)
AS
SELECT LastName, FirstName, #fieldvar1
FROM Certifications
WHERE Forms![F: Reports Switchboard]![Machine Name]>""
GO
But again, I just get the field name in the query, not the record data for the field.
I think I am missing something obvious, but I need a push in the right direction. Any help would be appreciated.
Since the machine name is a column of table, it is a structural component of the SQL statement and not string literal. Hence, you need to create a dynamic query object which you can handle in VBA using QueryDefs:
Dim qDef As QueryDef
Dim strSQL As String
strSQL = "SELECT LastName, FirstName, " _
& "[" & Forms![F: Reports Switchboard]![Machine Name] & "] As MachineDate " _
& "FROM Certifications " _
& "WHERE [" & Forms![F: Reports Switchboard]![Machine Name] & "] >'' "
Set qdef = CurrentDb.QueryDefs("mySavedQuery") ' LOCATE SAVED QUERY
qdef.SQL = strSQL ' CHANGE ITS SQL
Set qdef = Nothing ' RELEASE OBJECT TO SAVE
But ideally if you can avoid wide formatted data since you never want to save data elements in column headers. As one DBA guru says, Why would you need to create a table with even 20 columns, let alone 2000 ???.
Instead use a more normalized, long table format and avoid complex queries:
LastName
FirstName
Machine
Date
Stacks
Rick
Machine01
5/1/21
Stacks
Rick
Machine02
5/15/21
Stacks
Rick
Machine03
5/20/21
...
...
...
...
Doing so, requires no VBA but a single, static SQL query:
SELECT LastName, FirstName, Machine, [Date]
FROM Certifications
WHERE Machine = Forms![F: Reports Switchboard]![Machine Name]
Table and Field names cannot be dynamic in Access query object.
I will assume there is a unique identifier field something like EmpID. If there isn't, there should be.
Possible options:
every machine field would have same criteria with OR operator - 50 fields might hit limit on number of OR operators, apparently there is a limit of 99 AND operators
build a UNION query to rearrange machine fields to normalized structure and use that query as source for another query to do search - UNION has a limit of 50 SELECT lines so might just barely work and there is no builder or wizard for UNION, must type or copy/paste in SQLView
SELECT EmpID, LastName, FirstName, Machine01 AS CertDate, "Machine01" AS MachineName FROM Certifications
UNION SELECT EmpID, LastName, FirstName, Machine02, "Machine02" FROM Certifications
...;
use DLookup domain aggregate function on designated machine field, reference form control for field argument input
SELECT EmpID, LastName, FirstName, Forms![F: Reports Switchboard]![Machine Name] AS MachineName,
DLookup("[" & Forms![F: Reports Switchboard]![Machine Name] & "]", "Certifications", "EmpID=" & [EmpID]) AS CertDate
FROM Certifications;
VBA and QueryDefs to modify query object

Multiple rows in singleton select: How to make several results appear?

I am currently trying to make several telephone-numbers appear in NetBeans, but it would seem the SQL query for my database is far from perfect. It always tells me: Multiple rows in singleton select.
The code allows me to get one number if it only belongs to one person, there is however one number that belongs to three people, and I need all of those three to appear. Thanks in advance!
String telephoneQuery3 = "select * from HAS_COMPETENCE where aid = (select aid from EMPLOYEE where telephone = '" + telephone + "')";
You are using = when you should use in:
select *
from HAS_COMPETENCE hc
where hc.aid in (select e.aid from EMPLOYEE e where e.telephone = '" + telephone + "')
The problem is that the subquery is returning more than one value. With =, the engine expects only one value. The in fixes this so it expects a list of values.
I also added table aliases to the query. This identifies which tables the fields are coming from -- to avoid confusion for someone looking at the query.
Comparing with = only works if the expression to its right returns one row, insetad use IN
select * from HAS_COMPETENCE where aid IN (select aid from EMPLOYEE where telephone = '" + telephone + "')";

I have an error saying "Subquery returns more than 1 row "

String sqlStr = "SELECT *,"
+"(SELECT group_concat(gGenre) FROM spmovy_genre_table a,spmovy_genre b WHERE mID=mID "
+"AND a.gID=b.gID group by mID) Genre "
+"FROM spmovy_movie where mTitle "
+ "like ?";
I have a table fill with movie titles joined by a foreign key Genre table with gID, 1. table with movie title and mID then a second table with mgID, mID, gID to link with a third table with gID and gGenre
Apart from general comments about your query (learn join syntax and use descriptive aliases), the problem with your query is the line:
mID = mID
in the not-quite-correlated subquery.
You are trying to get one set of genres. But the query is returning one for each group. And in a select within a select, you can't have multiple values.
You intend for this to correlate the subquery, but it is not. You need table aliases for that. Here is my guess as the right version:
SELECT *,
(SELECT group_concat(gGenre)
FROM spmovy_genre_table a join
spmovy_genre b
on a.gID=b.gID
WHERE spmovy_movie.mID=b.mID
) Genre
FROM spmovy_movie
where mTitle like ?
The match could be to a.mID rather than to b.mID.
I also removed the group by clause, since that is no longer necessary.

match the names

I have two tables. CustomersTable and BusinessDirectory
Both tables have a column called businessName.
my CustomerTable has a columns cid, customerID, businessName
my BusinessDirectory table has columns bdid, businessName, getID
I want to update the getID field in BusinessDirectory table by customerID in CustomerTable where the business name matches in CustomerTable. Hence I did this query
update BusinessDirectory INNER JOIN CustomerTable ON CustomerTable.businessName = BusinessDirectory.businessName set BusinessDirectory.getID = CustomerTable.customerID;
which updates the records fine as long as the records match 100%. There are some records where there is a little typo and stuff
like I have a business name General Contractors Inc in one table and the other table has it as General Contractors. As you can see its missing Inc, so it doesnt match. What can I do to get best possible matches.
Thanks
This should work, but it is not particularly safe:
UPDATE BusinessDirectory, CustomerTable
SET BusinessDirectory.getID = CustomerTable.customerID
WHERE BusinessDirectory.businessName Like
Left(CustomerTable.businessName,InstrRev(CustomerTable.businessName," ")) & "*"