I have the following situation:
1 Table for a Warehouse where I have: the ProductID, the qty and the address 1 Table for the Stores Where I have: The ProductID and qty 1 table for the Stores Storage addresses
What I need to know is if a product is "in Stock" or "out of Stock" using the criteria that for a product to be considered "out of stock" it has to have qty >=0 or >20k in both tables (stores and warehouse)
What I have tried is the following:
SELECT Product_Cod, qty_wh, QtyStore,
CASE
WHEN sum(QtyStore) BETWEEN 1 AND 20000 THEN
CASE
WHEN qty_wh > 0 THEN 'In Stock'
WHEN qty_wh = 0 THEN 'In Stock'
END
WHEN sum(QtyStore) = 0 OR sum(QtyStore) > 20000 THEN
CASE
WHEN qty_wh <= 0 THEN 'Out of Stock'
WHEN qty_wh > 0 THEN 'in Stock'
END
END AS [Result]
FROM tb_Products, tb_qtyStock, tb_StoreProdAddress
WHERE Product_Cod = wh_CodProduct
AND Product_Cod = Store_CodProduct
GROUP BY Product_Cod, qty_wh, QtyStore
ORDER BY Product_Cod
Which outputs:
ProdCod qty_wh QtyStore Result
10026 26 0 In Stock
10026 26 1 In Stock
10026 26 2 In Stock
10070 25 0 In Stock
10070 25 2 In Stock
10070 25 3 In Stock
10071 20 0 In Stock
10071 20 1 In Stock
10071 20 29991 In Stock
10072 32 0 In Stock
10072 32 1 In Stock
10072 32 29978 In Stock
10204 0 0 Out of Stock
10204 0 1 In Stock
10204 0 4 In Stock
10204 0 29996 Out of Stock
But I can't make it work like I want because the QtyStore column doesn't SUM() it repeats because the tb_StoreProdAddress is used for several stores so Multiple stores can have the same product but each store may have a different address for that product, but the address for given product in the warehouse is the same.
There is a way to SUM() the QtyStore column and just Group the qty_wh ???
QtyStorecolumn out of the group by clause?