Assistance with msaccess sql query - sql

I have a form called “Search” with the question regarding the section under Transaction Search. It invokes a query based on the selection of full name (Combo40) which pulls from a table called “Individuals” and the committee(s) the user selected in Combo40 has contributed to in the Committee field:
Committee Query:
SELECT Transactions.[Committee Name] FROM Transactions GROUP BY Transactions.[Committee Name], Transactions.[Employee Name] HAVING (((Transactions.[Employee Name])=[Forms]![Search]![Combo40]));
I’m trying to add an additional parameter that also compares the year in which an individual gave which is a specific filed in the Transactions table called Combo46.
New Query:
SELECT Transactions.[Committee Name] FROM Transactions GROUP BY Transactions. [Committee Name], Transactions.[Employee Name] HAVING (((Transactions.[Employee Name])=Forms!Search!Combo40) And (((Transactions.Combo46)=Forms!Search!Combo51)))
Forms!Search!Combo40 = pulls the values from a table called “Individuals”
Transactions.Combo46 = year (i.e. 2011, 2012, 2013 etc.)
Forms!Search!Combo51 = year (i.e. 2011, 2012, 2013 etc.)
When I make my selections on the form I get a window that asks me to enter the value for Combo 46 and the committee list displays all records for that individual and not just transactions with the year I entered. I would expect it to not come up with a pop-up at all but instead take the value from Combo46 in the Transactions table and compare it to the value entered in Combo51.

It's too long and unclear for a comment, so I use this anwser space:
I suppose that the table column Transactions.Combo46 does not exist, so Transactions.Combo46 is popuped by Access for Input, it should be Transactions.Year or something meaning this:
SELECT Transactions.[Committee Name]
FROM Transactions
GROUP BY Transactions.[Committee Name], Transactions.[Employee Name]
HAVING (((Transactions.[Employee Name])=Forms!Search!Combo40)
And (((Transactions.Year)=Forms!Search!Combo51)))

What jacouh says is surely the answer (i.e., your SQL is referring to Combo46 as a member of Transactions when it is a member of Forms!Search). As an appendum, I'd simplify things a bit like this:
(1) Name the combo boxes something sensible (e.g. cboName and cboYear) rather than leaving them as Combo40 and Combo51 (yuck!).
(2) The GROUP BY seems unnecessary to me:
SELECT DISTINCT [Committee Name] FROM Transactions
WHERE ([Employee Name] = Forms!Search!cboName) AND ([Year] = Forms!Search!cboYear)

Related

SQL sum, multiple Group By's and Date criteria

I'm looking to perform a sum calculation on a SQL table to find the quantity of a particular stock item held against a particular salesperson up to and including a specific date.
I'm able to perform the sum function to find the quantities on a Salesperson/item basis whenever I do not factor in the date range criteria, but as soon as i add that aspect, it all goes a bit pear shaped! Here is my code so far:
SELECT Salesperson, Item No, Sum(Quantity) AS 'Quantity'
FROM dbo
WHERE (Location Code='VAN')
GROUP BY Salesperson, Item No,
HAVING (Registering Date<={ts '2017-05-03 00:00:00'})
The location code = VAN filter is required to ensure it ignores Warehouse quantities.My SQL knowledge is limited to the few instances I run into it at work and my interaction is largely based through Microsoft Query in Excel. When looking at the above code, i figured that the 'Registering date' criteria should be in the 'WHERE' section, however when i add the criteria using the options available in Microsoft Query, it creates the 'HAVING' line.
If anyone could provide any pointers, it would be much appreciated!
Cheers
Peter
I would imagine a query like this:
SELECT Salesperson, [Item No], Sum(Quantity) AS Quantity
--------------------^ escape the non-standard column name
FROM dbo.??
---------^ table name goes here
WHERE Location Code = 'VAN' AND
[Registering Date] <= '2017-05-03'
------^ put the filtering condition in the correct clause
GROUP BY Salesperson, Item No
-----------------------------^ remove the comma
Your code, as written, has multiple errors. I am guessing that most are transcription errors rather than in the original query (queries don't run if no table is given in the FROM for instance). The "major" error would then be filtering in the HAVING clause rather than the WHERE clause.

Remaining calculation

I have a database in MS Office Access, used to manage stock. I have two types of transactions Addition = when there is a new item, removal = when items go out.
I need to add a section that will return remaining quantity in stock after I add or remove items. What would you suggest?
Note: I have many items, not one item
What do you mean by 'add a section'? Calculate inventory balance when needed. Search topic 'inventory balance'. Could do an aggregate query for stock received and another for stock used then use those queries in another to calculate difference. Or consider:
SELECT [Transaction Item], Sum(IIf([Transaction Type]="Addition", [Quantity],0)) - Sum(IIf([Transaction Type]="Removal", [Quantity],0)) AS Balance GROUP BY [Transaction Item];
A running balance on form is not practical (not to mention just plain hard to do) especially if records are filtered or sorted. However, you could show the net balance of each item with DSum() domain aggregate function. Try this in the [Inventory Transactions Extended] query.
Balance: Nz(DSum("Quantity","[Inventory Transactions]","[Transaction Type]=1 AND [Transaction Item]=" & [Transaction Item]),0)-Nz(DSum("Quantity","[Inventory Transactions]","[Transaction Type]=2 AND [Transaction Item]=" & [Transaction Item]),0)
The calc will update as soon as record is committed to table. Record is committed when moving to another record, closing form, or by code to save record.
I NEVER build lookups in tables. I want to see the real values when I view tables.
Don't really need to pull [Inventory Transactions] ID field individually to define sort criteria. This is primary key index and records will sort by this field by default. So pulling in the field with the query * wildcard will produce the same sort.

Access VBA using SQL for importing multiple tables and then ensuring that they are union

Okay I am getting stuck with my code.
What I am trying to do is use specific data from multiple tables, but I want to use basically the UNION ALL and INNER JOIN functions, however, this is not supported with the Visual Basic of Access and I require it to go to a table so that I can proceed to my next step.
The whole interface work from a form that has buttons to press for normal users, basically setting up a whole interface for importing the reports.
My original import followed the advise that I received from here for the tables:
strSQL = "INSERT INTO [Clicks Returns] " & _
"(SKU, [Item Description], [Jan 2016 FIN YTD TY % Returns]) " & _
"SELECT Sku, [Item Description], [Jan 2016 FIN YTD TY % Returns] FROM [Jan 2016 Clicks Returns];"
DoCmd.RunSQL strSQL
This works perfectly for appending the data to one table, however when importing the data from multiple tables into one table it follows this pattern:
Result Example
However, I require this to be the result:
Required Result
The issue is that Both SKU numbers would be similar and the Item Desc. would be the same.
And with the normal append method it just keep duplicating and I want it to follow a join type action, and I do not know how to approach this exactly with Visual Basics on Access.
Thank you for taking the time to review this and also providing assistance.
with getting the information from the second table, you require the table to be updated. (so insert into won't work for the second time you need to get data...)
I would however reconsider your data structure, to have 1 data column in the table, and have 1 column indicating which month. Then when reporting you can pivot that information...
so basically this table format:
1) SKU
2) Item Description
3) Month
4) Month YTD information.
In the case above, your insert into will much more easily work, and you won't need an update statement.
I hope this helps.
Kind regards,

count unique for field in crosstab query

I've searched for an answer to this, but can't seem to find anything that works to do a unique count in crosstabs. The closest I could find was: select count(myField) from (select distinct myField from myTable), but I keep getting errors.
The training type is in columns, the dates in rows (formatted to month so I can separate out quarters or individual months), and ideally I would have the values as number of unique trainees that are identified by their Grower Record IDs. It currently displays all trainees who have been to the same training multiple times.
Any help would be greatly appreciated! Below is the SQL. Thanks for your time!
SQL:
TRANSFORM Count([TDB - Master - Trainee Attendence].[Grower Record ID]) AS [CountOfGrower Record ID]
SELECT Format([Dat Fòmasyon],'mm/yy') AS Months, Count([TDB - Master - Trainee Attendence].[Grower Record ID]) AS [Total Of Grower Record ID]
FROM [TDB - Master - Trainee Attendence]
WHERE (((Format([Dat Fòmasyon],'mm/yy'))="01/13" Or (Format([Dat Fòmasyon],'mm/yy'))="02/13"))
GROUP BY Format([Dat Fòmasyon],'mm/yy')
PIVOT [TDB - Master - Trainee Attendence].[Tit Fòmasyon an];
I would suggest that you create a query of the data you want to report (presumably):
SELECT DISTINCT [Grower Record ID], [Dat Fomasyon], [Tit Fomasyon an]
FROM [TDB - Master - Trainee Attendance]
Then generate a pivottable using this query as the data source.
Now I am not completely familiar with access's nuances, and dont know for certain that you can generate a pivottable from a query, but if not, I'd suggest changing your code (in a clone of the form) to do the same thing, replacing the from clause with a [aliased] query (and removing the references to the base table appearing in other clauses):
TRANSFORM Count([Grower Record ID] AS [CountOfGrower Record ID]
SELECT Format([Dat Fomasyon], 'mm/yy' AS Months, Count([Grower Record ID]) as [Total of Grower Record ID]
FROM (SELECT DISTINCT [Grower Record ID], [Dat Fomasyon], [Tit Fomasyon]
FROM [TDB - Master - Trainee Attendance]) Uniq
WHERE Format([Dat Fòmasyon],'mm/yy') = "01/13" Or Format([Dat Fòmasyon],'mm/yy' = "02/13"
GROUP BY Format([Dat Fòmasyon],'mm/yy')
PIVOT [Tit Fòmasyon an]
Note, I couldnt help thinking while rewriting the logic that it has been editted since being generated, as the name of the count (in [] after "AS") is different in the transform and select lines. I wouldnt expect this to matter, though in access you never know.
Hope this helps...
Please mark as answer if this helps you.

Calculated field with Sum IFF in MS Access 2010: Query and Expression Builder

In MS Access 2010, I successfully wrote a query that gives me the following fields from two seperate tables: [Customer ID], [Product], [Price], [Total Price] and [Payment Method]
A customer could have order different product or use different payment method. Now, I am trying to have a calculated field that will give the total/sum of only the products that were paid online by each customer.
The [Payment Method] code for online is a "D". I used the code builder expression with the following expression:
1) Sum(IIf([Customer ID] = [Customer ID] AND [Payment Method] = "D", [Price], NULL))
However, it keeps on giving me this error message: You tried to execute a query that does not inclide the specified expression "Customer ID" as part of aggregate function.
If I want to do it in SQL (or expression builder) how would I do it? Everything I've tried so far leads me to the same error message.
Edit
My full query is:
SELECT CUSTOMER_INFO.ID AS [Customer ID],
CUSTOMER_INFO.PROD_KEY AS [Product],
CUSTOMER_INFO.PROD_PRICE AS [Price],
CUSTOMER_INFO.SUM_PRICE AS [Total Price],
PAYMENT_TRANZAK.PAY_METHD,
Sum(IIf([Customer ID]=[Customer ID] And [PAY_MTHD]="D",[Price],[IsNull])) AS [Online Total]
FROM CUSTOMER_INFO INNER JOIN PAYMENT_TRANZAK ON (CUSTOMER_INFO.PROD_KEY= PAYMENT_TRANZAK.SSBSECT_CRN) AND (CUSTOMER_INFO.TERM_CODE_KEY = PAYMENT_TRANZAK.DATE_CODE)
WHERE (
((CUSTOMER_INFO.SUM_PRICE)>0) AND ((PAYMENT_TRANZAK.PAY_METHD) Is Not Null) AND ((CUSTOMER_INFO.CUST_CODE)="RE" Or (CUSTOMER_INFO.CUST_CODE)="RW") AND ((CUSTOMER_INFO.DATE_CODE)=[Please enter a transaction date: ]) AND ((CUSTOMER_INFO.ESTS_CODE)="EL") AND ((CUSTOMER_INFO.STST_CODE)="AS")
)
ORDER BY CUSTOMER_INFO.ID;
You're trying to perform aggregation on non-aggregated data. In order to do a sum the function needs something over which to sum; a "group" of data. Hence you will need a Group By clause in there. Adding the clause GROUP BY CUSTOMER_INFO.ID will create a sum of the totals for each customer ID. You can add your payment type clause to the where statement, too, to get the proper payment type logic.
SELECT CUSTOMER_INFO.ID AS [Customer ID]
, Sum([Price]) AS [Online Total]
FROM CUSTOMER_INFO
INNER JOIN PAYMENT_TRANZAK
ON (CUSTOMER_INFO.PROD_KEY= PAYMENT_TRANZAK.SSBSECT_CRN)
AND (CUSTOMER_INFO.TERM_CODE_KEY = PAYMENT_TRANZAK.DATE_CODE)
WHERE (((CUSTOMER_INFO.SUM_PRICE)>0)
AND ((PAYMENT_TRANZAK.PAY_METHD) Is Not Null)
AND ((CUSTOMER_INFO.CUST_CODE)="RE" Or (CUSTOMER_INFO.CUST_CODE)="RW")
AND ((CUSTOMER_INFO.DATE_CODE)=[Please enter a transaction date: ])
AND ((CUSTOMER_INFO.ESTS_CODE)="EL")
AND ((CUSTOMER_INFO.STST_CODE)="AS"))
AND PAYMENT_TRANZAK.PAY_METHD="D"
GROUP BY CUSTOMER_INFO.ID
ORDER BY CUSTOMER_INFO.ID;
Because you are not aggregating all the fields of not all the fields are being grouped by it is not possible to express them in this kind of query. These
CUSTOMER_INFO.PROD_KEY AS [Product]
CUSTOMER_INFO.PROD_PRICE AS [Price]
CUSTOMER_INFO.SUM_PRICE AS [Total Price]
PAYMENT_TRANZAK.PAY_METHD
thus aren't a good match.
But you know your data better than me, maybe there's a way to fit them in logically. that's up to you.
Edit:
You could try a query like this where you don't do any filtering but you jsut do your grouping. This will present everything then you do the filtering on your report or form.
SELECT CUSTOMER_INFO.ID AS [Customer ID]
, CUSTOMER_INFO.CUST_CODE
, Sum(CUSTOMER_INFO.PROD_PRICE) AS [Online Total]
, Sum(CUSTOMER_INFO.SUM_PRICE) as [SumOfSumPrice]
, CUSTOMER_INFO.CUST_CODE
, PAYMENT_TRANZAK.PAY_METHD
, CUSTOMER_INFO.DATE_CODE
, CUSTOMER_INFO.ESTS_CODE
, CUSTOMER_INFO.STST_CODE
FROM CUSTOMER_INFO
INNER JOIN PAYMENT_TRANZAK
ON (CUSTOMER_INFO.PROD_KEY= PAYMENT_TRANZAK.SSBSECT_CRN)
AND (CUSTOMER_INFO.TERM_CODE_KEY = PAYMENT_TRANZAK.DATE_CODE)
GROUP BY CUSTOMER_INFO.ID
, CUSTOMER_INFO.CUST_CODE
, PAYMENT_TRANZAK.PAY_METHD
, CUSTOMER_INFO.DATE_CODE
, CUSTOMER_INFO.ESTS_CODE
, CUSTOMER_INFO.STST_CODE
ORDER BY CUSTOMER_INFO.ID;
In MS SQL SERVER, ORACLE, MS ACCESS you need to add all other fields in select clause into aggregate clause.
It may help to start with what Access Help has to say on the subject :
Jet SQL Help:All fields in the SELECT field list must either be included in the GROUP BY clause or be included as arguments to an SQL aggregate function.This quote from the Help system implies that all references to fields, even within compound references, must either be aggregated (IE. included in one of the aggregate functions listed above) or included in the GROUP BY clause. Any expression which is of either type is considered aggregated. The aggregate functions can only take field reference expressions which resolve to non-aggregated fields (IE. It is equally invalid to aggregate data more than once).
reference
Since aggregate function is anyway aggregating your query, you may try it without group by clause and see.
Or you could include each of those fields. Issue might be mainly in your case, you have two different fields within the IIF yet having nulls not handled. For an aggregate I would use a zero or make sure to have Isnull to sum IIF.
PS: I sent answer from mobile and it seems the full answer has not been published the first time.