I have 2 Tables in MySQL
First is Sale and second is Purchase I want to see a Stock
this is My sale table that contains
Date Quantity ProductName
this is My Purchase Table that Contains sane attributes as sale have
I perform a Query but i Can not get my desire output
SELECT sale.Date, sale.ProductName, SUM(sale.StockQuantityIn) as StockIN,
SUM(purchase.StockQuantityout) as Stockout,
(SUM(sale.StockQuantityIn)-SUM(purchase.StockQuantityout)) as stock
from sale
join purchase on purchase.ProductName=sale.ProductName
GROUP BY sale.Date,purchase.Date ,purchase.ProductName,sale.ProductName
this is the Query and Result is noy my desired output
You cannot join the two tables as you did.
When you join two tables, you can imagine (it is not what really happens, but it helps to understand the result) that all the possible combinations of their rows are evaluated and later filtered based on the "where" constraints.
Try to simulate this process and you will see that the result is what you would expect.
It's not very good to JOIN, since each line in each table will appear as many times as matched in second table. This is why you get all these extra stockOut.
I would UNION 2 queries, one on sale, one on purchase, with ProductName, Date, and StockIn (which would be negative for the query on purchase)
Then I would GROUP BY ProductName and Date and SUM StockIn
Related
I am working on some practice interview Questions and am struggling with this:
You are working with a company that sells goods to customers, and they'd like to keep track
of the unique items each customer has bought. The database is composed of two tables:
Customers and Orders. The two table schemas are given below. We want to know what
unique items were purchased by a specific customer, Wilbur, and when they were
purchased. What is the correct query that returns the customer first name, item
purchased, and purchase date with recent purchases first?
Tables: https://imgur.com/a/D47R1KU
My answer so far is
However I am getting an incorrect message as its Printing wilbur,oranges,2019-06-10
and wilbur,oranges,2018-06-10 instead of just the one with the more recent date. Please see the picture for the two tables referenced by the question. Thanks!
Between the where clause and ORDER BY, try:
GROUP BY FirstName, Item
And to get the most recent date, select MAX(PurchaseDate).
The query you are looking for is as follows.
This uses group by to indicate which columns should be grouped together, and for the column that's not grouped, how to choose which value of many to use, in this case the max value.
Note also the use of explicit, clear, SQL-92 modern join syntax and meaningful column aliases to show which table each column originates from. Distinct is not needed since each group is already unique.
Select c.FirstName, o.Item, Max(o.PurchaseDate) PurchaseDate
from Customers c
join Orders o on o.PersonId=p.PersonId
where c.FirstName = 'Wilbur'
group by c.firstName, o.Item
order by Max(o.PurchaseDate) desc;
I got a table StockMovements which records all movements of my
products. It has a field named "Status", which can have either the
value Sold or Purchased, Quantity and Product (there are few more but
arent important now).
I made a query to take all the products with the status "Purchased"
and to take the quantity and named it Purchased Products (From the
table StockMovements). I have just sum the quantity and got the
purchased quantity for the each product (named the field Purchased).
I made another query, all the same just with the Status of Sold.
After I made a new query with the name Stock. Its built of the table
Products and the 2 queries I mentioned above. It takes the prodict_ID
and the product name from the table Product, the purchased field from
the first query and the Sold field from the second query and then a
final field not connected to any of above but a calculation. Named it
AvailableQuantity and added next with expression builder to it
=[Purchased] - [Sold].
Now when I run the query it works fine, except one thing. When I have
a specific quantity of a purchased product which I havent sold to
anyone yet (not even 1 piece) it doesnt want to show up in the query.
I want the product to show in the query and that the available
quantity is the purchased quantity. So somehow to skip the Sold value
if its 0 and just to write the Purchased quantity to that field.
When you have no sold qty your sum effectively becomes Purchased-Null which will result in no answer.
You should allow for nulls by using [Purchased] - (Nz([Sold],0)) which will force a zero into the calculation.
I went into the SQL view and changed the INNER JOIN to RIGHT JOIN, it did the job.
SELECT tblProduct.Product_ID, tblProduct.ProductName, Nz([Purchased],0) AS
PurchasedQuantity, Nz([Sold],0) AS SoldQuantity, [PurchasedQuantity]-(Nz([SoldQuantity],0))
AS [Available] FROM qrySoldProducts RIGHT JOIN (qryPurchasedProducts RIGHT JOIN
tblProduct ON qryPurchasedProducts.Product_ID = tblProduct.Product_ID) ON
qrySoldProducts.Product_ID = tblProduct.Product_ID;
I have three tables: product, sales_order (where I sell products) and purchase_order (where I buy products). Now I can think of two ways of keeping the quantity of each product:
Have a column in the product table called quantity; when inserting into sales_order, I subtract the quantity; when inserting into purchase_order, I add the quantity
Instead of storing the quantity in the product table, I calculate the quantity from the sales_order and the purchase_order table each time I need to get the product table
I am wondering if the second approach is preferable to the first one? I like the second one more because it doesn't store any redundant data; however, I am not so sure if calculating the quantity every time is a bit too much calculation. I am wondering what is the convention and best practice here? Thank you!
I would use the first one. Add a column to the product table in the coding u code -x amount when order and you would then display this in the order table. You could right a script for when the products get to a certain amount it emails you and tells u to replenish stocks. However the second would also work and sql is very powerful so i wouldnt wprry about it being ro demanding as it will prbably work it out faster than we can lol
I prefer the first one because in-memory calculations are faster than issuing select statements to check the sales orders and purchase orders assuming that the number of times the quantity value is retrieved is significantly more than the number of times the quantity value is updated.
Say there is an SQL table
SHIPMENTS(ProductNumber, ClientNumber, Quantity)
(1,1,4)
(2,5,2)
(1,1,2)
(4,1,5)
(2,5,3)
In the example above we notice that client #1 has made three purchases (twice the same product). Hence, the answer should be 2 since we're looking for the number of DIFFERENT products purchased by that client.
Applying this query
SELECT count(*)
FROM SHIPMENTS
WHERE ClientNumber = 1;
Will understandably give 3 as a result. And I can't think of the solution as to how to calculate only for the different products.
SELECT count(DISTINCT ProductNumber)
FROM SHIPMENTS
WHERE ClientNumber = 1;
This should do the trick. Adding DISTINCT takes every unique value once:
http://www.w3schools.com/sql/sql_distinct.asp
I am joining two tables (shipments and returns) and using group by to view totals for certain criteria. The two tables are related via shipment_id. this column is mostly unique, but contains a few duplicates because each shipment can contain more than one item that is also contained in the table.
I'm trying to count all the distinct shipments grouped by warehouse, seller, and size. count(distinct works great, but does not report correct information when used with group by if the range of items being grouped is significant.
The query below returns 7 shipments (added up) 4 returns (also added). While with the small amount of test data I have the return count is correct, there are in actuality 6 distinct shipments, not 7. With this query i'm basically looking at all shipments and joining return information if an item in the shipment has been returned.
select s.warehouse, s.seller, s.size,
count(distinct s.shipment_id) as total_shipments,
count(distinct r.shipment_id) as total_returns
from shipments s
left join returns r
on s.shipment_id = r.shipment_id
group by s.warehouse, s.seller, s.size
I'm concerned that the report I generate won't be entirely accurate. Is there a work around for this issue? I've seen similar issues, but none that really apply. I am using MYSQL
I see a potential problem. If a shipment has multiple items and may end up in duplicate shipment records, that means that it's possible that the shipment comes from different warehouses or sellers or that the size is different. By grouping by those fields, you risk ending with with shipment being calculated more then once since the shipment_id is technically distinct for that group.
You could try grouping by s.shipment_id instead of s.warehouse, s.seller, s.size. The problem here is that if the warehouse, seller or size differs, you'll end up missing one row (for that warehouse/selling/size) but the totals will add up.