Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I need to arrive Remaining Stock from products. I have 3 Tables Product, Sold, ReceivedProducts

ProductStock Table
C#
ProductId   ProductName  InitialQuantity
1           Mobile       50
2           Charger      30
3           Torch Light  50
4           Laptop       40      


ReceivedProducts Table
C#
Product(Product Id)    ReceivedQty
2                      20
2                      5


Sold Table
C#
ItemId   Quantity   Amount
4         3         90,000
1         10        5,000

Now i need to get remaining Stock that is ((Initial Qty + Received Qty) - Sold Qty )
so i tried this query to join initial qty and Received Qty but getting error like At most one record can return by sub query
SQL
SELECT ProductId, InitialStock, 
(SELECT ReceivedQty FROM ReceivedProducts WHERE Product=ProductStock.ProductId) AS ReceivedStock FROM ProductStock;


this below query working but getting only one product because received product is twice same so. I need to add initial stock if received quantity is not available also. How to form query ??
(Initial Qty + Received Qty)
SQL
SELECT ProductId, 
InitialStock+SUM(ReceivedQty) AS TotalQty 
FROM ProductStock AS PSD INNER JOIN ReceivedProducts AS RP ON PSD.ProductId=RP.Product
GROUP BY PSD.ProductId,InitialStock;
Help me to solve this

Thanks in advance
Sri
Posted
Updated 2-Apr-14 22:14pm
v4

1 solution

Hi,

You're getting only one product because you're using INNER JOIN. So use LEFT JOIN instead. Also, you need to replace NULL values with 0. Your query should be like this:
SQL
SELECT ProductId, IIF(InitialStock IS NULL, 0, InitialStock) + SUM(IIF(ReceivedQty IS NULL, 0, ReceivedQty)) AS TotalQty
FROM ProductStock AS PSD LEFT JOIN ReceivedProducts AS RP ON PSD.ProductId = RP.Product
GROUP BY PSD.ProductId, InitialStock;

Please let me know how it works.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900