Access query: Average multiple cells in One column - ms-access

What Im trying to do is create a shipping estimator if you will. At this point ups and fedex have volume based prices and unfortunately my vendor doesnt supply dimensions for each product. However they do offer weights.
In table one I have Part#, weight, and price of shipping of past shipments.
In table Two I have Part#, weight of never been shipped items.
What I would like it to do:
set up a query that will take products from table 2 and find like weighted items from table 1, average there shipping prices and us this new number as the estimated shipping for the new product. The part im having a hard time wrapping my head around is searching for a range of weights. Lets say my product is 5lbs and I want to get shipping prices of all products ranging form 4.75 to 5.25.
My knowledge of access is somewhat limited. I would really appreciate some guidance here.

SELECT PartsUnshipped.PartNr, PartsUnshipped.Weight,
(SELECT AVG([ShipPrice]) FROM [PartsShipped]
WHERE [PartsShipped].[Weight] >=[PartsUnshipped].[Weight]-0.25
And [PartsShipped].[Weight] <=[PartsUnshipped].[Weight]+0.25) AS Estimated
FROM PartsUnshipped
This is one way to do it. Another way would be to simply join the two tables and run an Avg on the Shipped price but then you would only return non-nulls.

Related

Trigger to add all prices of sold items and output to invoice table

I have three tables: items, sold, and invoice. The item table tracks individual item prices and descriptions, the sold table tracks items the belonging to a particular invoice, and Invoice tracks the date and other information. Invoice has a one-to-many relationship with sold and sold has a one-to-many relationship with items.
Here are the relevant columns in my tables: invoice(invoiceID, total) sold(soldID, invoiceID, itemID) item(itemID, description, price)
I currently have no way to track the total price for the invoice without manually summing the items. The total column in invoice must be manually inserted.
I'm looking to create a trigger the finds all the rows i sold that have a matching foreign key for invoiceID, then adds the prices of the relevant items and outputs that to invoice.
If this is not possible, I could also add a new price column to sold, then use multiple triggers to eventually work my way up to invoice.
I'm not in a position where I can make any significant changes to the structure of the database, so if possible it'd be best to keep the fields and relationships as is.
If anyone has any input on how to create this trigger it'll be greatly appreciated.
#stickybit is exactly right. You don't want redundant data. You should not put any sort of derived total in an invoice record. Instead you should get it with a query or a view.
It's sometimes hard for people new to using SQL to believe, but queries and views are typically just as quick for retrieving aggregates like totals.
Views and tables look precisely the same from the perspective of application software. So make a view of your invoices that shows the totals. Something like this.
CREATE OR REPLACE VIEW invoice_with_totals AS
SELECT sold.invoiceId, SUM(price) total
FROM sold
JOIN item ON sold.itemID = item.itemID
GROUP BY invoiceID
Believe it or not, doing things this way with views will save you (or the people who will use your application) all kinds of troubleshooting craziness in the future. If you do things this way, there's simply no possibility of your totals disagreeing with the details in your invoices. If you use a trigger, that's not guaranteed. And, you know, Murphy's law, big customer, incorrect invoice, you get the picture ....
I have hard-won experience backing up my suggestion. I suspect #stickybit does too. Please consider it.

Update one SQL value in a table after changing a value from another table

So I have a table categories with the following columns:
Id, Category, Vat, Tax
And a products tables with the following columns:
Id, idCategory, Code, Product, Stock, buyingPrice, sellingPrice, Sales
When creating a new product the value of a product is entered and the buyingPrice is calculated by adding the Vat and Tax from the categories table to the value.
The sellingPrice is then calculated by a percentage markup of the buying price.
I now want to be able to automatically update the buyingPrice of all products if the Vat or Tax is changed.
I have tried creating a trigger but I am currently unable to work it out. I'm not sure if it's because the original value is not saved or if I am doing it all wrong. I have never created a trigger before so any push in the right direction would be appreciated.
I think Strawberry has a great comment here; you should store the VAT and tax separately and apply them to the base price that you store, rather than storing it as a final selling price that includes VAT or tax.
In your scenario, what happens if the VAT is reduced by 0.5%? Your trigger can be modified to properly account for newly inserted items, but how will you go back and correct existing ones? In the US, an item can be exempt from sales tax (if the purchaser is a certain type of non-profit organization or other exempt business, or in certain states during a sales-tax holiday). Again, in the US, sales tax calculations regarding putting an item on sale can be complicated. I'm not making the assumption that your situation will require dealing with those situations, but it seems like it would benefit you to not need to recalculate every item in your database if any of these were to apply.
If you really insist on this, I'd personally rather use a view to calculate the price on the fly rather than using a trigger to calculate it on insertion, but that's just me. Again, I'd ultimately prefer to handle this in the application logic.

Stock management database design

I'm creating an Intranet for my company, and we want to have a stock management in it. We sell and rent alarm systems, and we want to have a good overview of what product is still in our offices, what has been rented or sold, at what time, etc.
At the moment I thought about this database design :
Everytime we create a new contract, this contract is about a location or a sale of an item. So we have an Product table (which is the type of product : alarms, alarm watches, etc.), and an Item table, which is the item itself, with it unique serial number. I thought about doing this, because I'll need to have a trace of where a specific item is, if it's at a client house (rented), if it's sold, etc. Products are related to a specific supplier, to whom we can take orders. But here, I have a problem, shouldn't the order table be related to Product ?
The main concern here is the link between Stock, Item, Movement stock. I wanted to create a design where I'd be able to see when a specific Item is pulled out of our stock, and when it enters the stock with the date. That's why I thought about a Movement_stock table. The Type_Movement is either In / Out.
But I'm a bit lost here, I really don't know how to do it nicely. That's why I'm asking for a bit of help.
I have the same need, and here is how I tackled your stock movement issue (which became my issue too).
In order to modelize stock movement (+/-), I have my supplying and my order tables. Supplying act as my +stock, and my orders my -stock.
If we stop to this, we could compute our actual stock which would be transcribed into this SQL query:
SELECT
id,
name,
sup.length - ord.length AS 'stock'
FROM
product
# Computes the number of items arrived
INNER JOIN (
SELECT
productId,
SUM(quantity) AS 'length'
FROM
supplying
WHERE
arrived IS TRUE
GROUP BY
productId
) AS sup ON sup.productId = product.id
# Computes the number of order
INNER JOIN (
SELECT
productId,
SUM(quantity) AS 'length'
FROM
product_order
GROUP BY
productId
) AS ord ON ord.productId = product.id
Which would give something like:
id name stock
=========================
1 ASUS Vivobook 3
2 HP Spectre 10
3 ASUS Zenbook 0
...
While this could save you one table, you will not be able to scale with it, hence the fact that most of the modelization (imho) use an intermediate stock table, mostly for performance concerns.
One of the downside is the data duplication, because you will need to rerun the query above to update your stock (see the updatedAt column).
The good side is client performance. You will deliver faster responses through your API.
I think another downside could be if you are managing high traffic store. You could imagine creating another table that stores the fact that a stock is being recomputed, and make the user wait until the recomputation is finished (push request or long polling) in order to check if every of his/her items are still available (stock >= user demand). But that is another deal...
Anyway even if the stock recomputation query is using anonymous subqueries, it should actually be quite fast enough in most of the relatively medium stores.
Note
You see in the product_order, I duplicated the price and the vat. This is for reliability reasons: to freeze the price at the moment of the purchase, and to be able to recompute the total with a lot of decimals (without loosing cents in the way).
Hope it helps someone passing by.
Edit
In practice, I use it with Laravel, and I use a console command, which will compute my product stock in batch (I also use an optional parameter to compute only for a certain product id), so my stock is always correct (relative to the query above), and I never manually update the stock table.
This is an interesting discussion and one that also could be augmented with stock availability as of a certain date...
This means storing:
Planned Orders for the Product on a certain date
Confirmed Orders as of a certain date
Orders Delivered
Orders Returned (especially if this is a hire product)
Each one of these product movements could be from and to a location
The user queries would then include:
What is my overall stock on hand
What is due to be delivered on a certain date
What will the stock on hand be as of a date overall
What will the stock on hand be as of a date for a location
The inventory design MUST take into account the queries and use cases of the users to determine design and also breaking normalisation rules to provide adequate performance at the right time.
Lots to consider and it all depends on the software use cases.

ACCESS - calculating prices

I have one table in my access DB which contains a list of all devices that has been sold to our customer. We have only one customer and only one type of device. The table contains details like name, serial, warranty detail of device. Now we need to calculate the price for invoice purpose. The thing is that the price should be calculated depending on amount of sold devices and also we don't want to hard code the price instead we would like to use a separate table whit different category of prices and calculating the price based on this table, because of the prices changing frequently and so we should modify the price value only in one table.
We have 3 category of price : if customer bought 100 device then the unit price is 15$ else if 200 devices the unit price would be 10$ else if 300 then price for unit would be 5$. So based on these rules we will need to calculate the price.
So I'm looking for the right approach that would be for this problem.
This is a very open-ended question and is impossible to definitively answer without more information about the architecture of the database.
There are 3 different ways I usually perform a calculation inside my Access databases.
perform a calculation inside a query. For simple things.
perform a calculation inside a module function, that is called by a query. For complicated things.
perform a calculation inside a module vba subroutine, that is called by a button OnClick Event. For extremely complicated things.
You could do a cross join as long as you have a range wide enough to account for all possibilities (i.e. some ridiculous upper boundary like 9999999). Otherwise a subquery would work with the same WHERE clause:
SELECT Prices.Price
FROM Prices
WHERE (Prices.MinQuantity <= Invoice.Quantity) AND
(Prices.MaxQuantity >= Invoice.Quantity)
As Gustav and V-ball point out there are many ways to set this up depending on your needs.

Interesting Database Architecture Scenario

I am currently in the process of rolling a custom order-processing system. My current structure is pretty standard, invoices, purchase orders, and items are all kept in separate tables. Items know which form(s) they are on by keeping track of the form's id, but forms don't know what items are in them (in the database). This was all well and good until I had a new requirement added to the mix: stocking orders.
The way a stocking order works is that sometimes a customer places an order for more units than what is in stock, so we want to place an order with our supplier for enough units to fulfill the order and replenish our stock. However, we often have to build these orders up as the minimums are pretty high, so one stocking order is usually comprised of several customer orders (sometimes for the same item) PLUS a few line items that are NOT connected to an order and are just for stocking purposes.
This presents a problem with my current architecture because I now need to keep track of what comes in from the stocking orders as often suppliers ship partial orders, where items have been allocated, and which incoming items are for stock.
My initial idea was to create a new database table that mostly mimics the items table, but is kind of like an aggregate (but not calculated) table that only keeps track of the items and their corresponding metadata (how many units received, how many for stock, etc) for only the stocking orders. I would have to keep the two tables in synch if something changed from one of them (like a quantity).
Is this overkill, and maybe there's a better way to do it? Database architecture is definitely not my forte, so I was hoping that someone could either tell me that this is an ok way to do things or that there is a better, more correct way to do it.
Thanks so much!
For what it's worth, what I'm using: VB, .NET 4.0, MySQL 5.0
Also, if you want clarification on anything, please ask! I will be closely monitoring this question.
Visit databaseanswers.com. Navigate to "free data models", and look for "Inventory Management". You should find some good examples.
you didnt mention them but you will need tables for:
SUPPLIERS, ORDERS, and INVENTORY
also, the base tables you mention 'knowing about' - these probably need associative style many to many tables which tell you things like which items are on which order, and which suppliers supply which items, lead times, costs etc.
it would be helpful to see your actual schema.
I use a single Documents table, with a DocType field. Client documents (Order, Invoice, ProForma, Delivery, Credit Notes) are mixed with Suppliers documents (PO, Reception).
This makes it quite easy to calculate Client backorders, Supplier backorders, etc...
I am just a bit unhappy because I have different tables for SUPPLIERS and CLIENTS, and therefore the DOCUMENTS table has both a SupplierId field and a ClientId field, which is a bit bad. If I had to redo it I might consider a single Companies table containing both Clients and Suppliers.
I use a PK (DocId) that's autoincrement, and a unique key (DocNum) that's like XYY00000, with
x= doc type
YY= year
00000 = increment.
This is because a doc can be saved but is only at validation time it receives a DocNum.
To track backorders (Supplier or Client), you will need to have a Grouping field in the DocDetails table, so that if you have an Order line 12345, you copy that Link field to every Detail line related to it (invoice, Delivery).
Hope I am not to confusing. The thing works well, after 3 years and over 50,000 docs.
This approach also implies that you will have a stock holding which is allocated for orders - without individual item tracking its a bit tricky to manage this. Consider, customer A orders
3 pink widgets
1 blue widget
But you only have 1 pink widget in stock - you order 3 pink widgets, and 1 blue.
Customer B orders
2 pink widgets
But you've still only got 1 in stock - you order another pink widget
3 pink widgets arrive from the first supplier order. What are you going to do? You can either reserve all of them for customer A's order and wait for the blue and red widget to arrive, or you can fulfill customer B's order.
What if the lead time on a pink widget is 3 days and for a blue widget it's 3 weeks? Do you ship partial orders to your customers? Do you have a limit on the amount of stock you will hold?
Just keeping a new table of backorders is not going to suffice.
This stuff gets scary complicated really quickly. You certainly need to spend a lot more time analysing the problem.