Remaining calculation - sql

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.

Related

How can I get accurate totals from a subform when in splitform view, currently each record needs to be selected before the total is correct

I am setting up a system for the reconciliation process of accounts payable. I set up a few tables for inputting the groups of tickets that we get every day to log them before we get in the invoices.
I have a handful of tables that provide information about some of the fields in the tables but the key tables are:
Ticket_Group:
TGID(autonumber)
Ticket_Date
SupplierID(Unique Identifier for Raw Material Provider)
ShipperID(Unique Identifier for Shipping Company of classification)
MaterialID(Unique Identifier for material)
gl_dep(general ledger department)
mat_inv_rec(true/false if material invoice has been received)
freight_inv_rec(true/false if freight invoice has been received)
Ticket:
TID(Autonumber for Each Ticket)
TGID(Links to TGID in Ticket_Group, Many TID to One TGID)
qty(Quantity of Material)
What I want to be able to do is see all of the Records from Ticket_Group that still have their invoices not received. But I also need to see the totals so I can match them correctly. Not exactly the ideal way to do AP reconciliation but it is much better than how we currently do it(pseudo-pivot table with supplier and shipper combinations along one side and days of the month along the top and individual tickets as values being added together in each cell).
What I have now is a splitform of the Ticket_Group table with the Ticket subform. I put a sum([qty]) in the footer of the subform and referenced that field in the mainform. This only half works because the total is right in the single form view but the datasheet view displays the selected records total as the total for all records until each individual record has been selected.
I thought maybe an onload event for the form that cycled through every record might work, but I figured there must be a better way.
I am super new with MS Access so I really appreciate the help!
Referring to the Subform-Field can't work because it refers to the actual (selected) record of the mainform.
That's why the Datasheet-View shows the value of the actual selected record of mainform for all records, because there is only one subform with the caclulated field that changes depending on the mainforms record, not a new one for every record of the mainform.
To get the value in the Datasheet-View get it from the tables, not the subform.
E.g. set the Control-Sourceof a TextBpx to:
=DSum("qty","Ticket","TGID = " & Ticket_Group.TGID)
or add the expression to yourForm.RecordSourceas a field like:
Select Ticket_Group.TGID, Ticket_Group.Ticket_Date, ... , DSum("qty","Ticket","TGID = " & Ticket_Group.TGID) as SumQty FROM Ticket_Group
to have the form editable.
Or join
Select TGID, Sum(qty) As SumTicketQty FROM Ticket Group By TGID
with your mainform's query and then bind it to the mainform, but that leads to a readonly query.

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.

Merging two different tables to form one but keeping related data

Im a little new to Acess and am trying to understand how to merge tables.
My problem is basically this...
I have 2 reports that can be ran and exported to excel. I want to be able to take both reports, combine them, and import the combined result to a table.
In one report.. call it location detail... has the following fields:
ID (PK, and autonumber)
Day (Date call was done)
CallID (Resets every day to 1, and increases by 1 for every new call)
Lat (Lattitude of call)
Long (Longitude of call)
Cost
In the other report.. call it location summary.. has the following fields:
ID (PK, and autonumber)
Location
City
Lat (Lattitude of call)
Long (Longitude of call)
# of Occurences (Number of times there was a call at that location)
The problem is when you have a call in the same location, even though it was on two seperate days, it automatically groups it into the number of occurances. So I tried to run 2 seperate queries from the same range of dates, one matching lat, other matching long, it shows up with duplicates.. my guess is because the ones that do not have a matching lat (because it already used the field once, even though there were 4 occurences) are showing null value and are added to the query as a duplicate.
I want to add the City Column that matches the long/lat data, to the location details report, and then make that into a new table/ and then be able to run the same reports, and add them to the new table, but somehow ensure there arent any duplicates.
My biggest problem is there isnt any real primary key since the Call ID is Dependent on the Date.... I am not sure how to really accomplish this.
Any help would be much appreciated... I am Stumped.
EDIT:
The first Query is to join lattitudes:
SELECT
[Location Detail Report_142].Day, [Location Detail Report_142].[Call ID],
[Location Detail Report_142].Lat, [Location Detail Report_142].Long
FROM [Location Detail Report_142]
LEFT JOIN [Location Summary Report_14]
ON [Location Detail Report_142].Lat = [Location Summary Report_14].Lat;
The second one matches call id:
SELECT qryRelationshipToLat.Day, qryRelationshipToLat.[Call ID],
[Location Summary Report_14].City
FROM [Location Summary Report_14]
INNER JOIN qryRelationshipToLat
ON [Location Summary Report_14].Long = qryRelationshipToLat.Long
ORDER BY qryRelationshipToLat.Day, [Location Summary Report_14].City;
I was thinking maybe it could be possible to make some sort of if-then statement stating that if call id shows duplicate THEN match Call ID... It has to match both, when the original Location Summary report is uploaded, it has 283 reccords, but it shows duplicate locations grouped into anouther field (#_of_Occurances), so the total amount of calls would be the total amount in the Location Detail report, witch in this case is 288. so when I run the first qry - 305 results, and the second qry turns the 305 to 337. So I end up with a lot of just duplicates I guess, or null value ones.
But the two reports both don't include Call ID or Call Numbers. The only information that they share is the LONG and LAT Coordinates. So I would have to match those first, then assign call ID, date, and city to the corresponding coordinates.
I think that you need to learn how to use a GROUP BY statement to aggregate your table. These links may help:
http://www.sqlteam.com/article/how-to-use-group-by-in-sql-server
http://beginner-sql-tutorial.com/sql-group-by-clause.htm
It's possible also that your table designs have to be revised, and presumably your approach for adding to the call record as well.
I'm sorry to just throw some links at you, but I'm not quite up to analyzing what you have got in order to construct a complete answer, and in any case I think you will have to tackle these areas of learning.

Assistance with msaccess sql query

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)

Calculate total number of items received when item is received on more than one shipment

I have a set of tables in Access 2007 that I need to get to display the total number of items received. We order items against a job using the job number as a common reference (like an ID).
Each job has multiple items required. Most items have multiple shipments we receive. Each shipment is given a unique receiving ticket number, so they need to be entered individually and totaled.
I have:
tblJobItems :JobNumber, Item, QtyNeeded
tblReceived :JobNumber, Item, QtyRecvd, RTNumber (RT = Receiving Ticket)
tblJobs : JobNumber, JobQty (and more, but not relevant to this issue)
(JobQty is not always the same as the item's QtyNeeded. The job is like a run of a certain model of computer, the job qty is how many of that model. Items are sometimes 1:1, like a case or power supply, but can be 2:1 or 3:1 like having multiple hard drives.)
I have a query that works fine to show the number of items placed on order, but we want to expand it (or combine with other queries) to show the total number of items received per the job number on the same line. Eventually I'll use this number to change the status and other functions.
SELECT tblJobItems.JobNumber, tblJobItems.Item, tblJobItems.QTYNeeded, tblJobItems.PartStatus, First(tblJobs.BDT) AS FirstOfBDT, First(DateAdd("ww",-2,[BDT])) AS DueBy
FROM tblJobItems INNER JOIN tblJobs ON tblJobItems.JobNumber = tblJobs.JobNumber
GROUP BY tblJobItems.JobNumber, tblJobItems.Item, tblJobItems.QTYNeeded, tblJobItems.PartStatus;
This shows me in a listbox the items ordered and how many, the JobNumber is stored as ([Tempvars]![JobNum]), and the listbox only shows the records that match the JubNumber. (the tempvar is global, so it can be used in a query if that helps anyone)
I'm not opposed to having this go through two or three queries to get to the answer.
It turns out that the key piece needed in my query's SQL was:
Sum(tblReceived.ReceivedQTY) AS SumOfReceivedQTY, IIf(IsNull([SumofReceivedQTY]),0,[SumofReceivedQTY]) AS RECQTY
This sums up the quantity and also creates a new column in the query with the totals.