Here is an example, hopefully it will fired you up! Assuming the order date is unique.
DECLARE @tblproducts TABLE (
product_barcode varchar(50) PRIMARY KEY NOT NULL,
product_name varchar(50) NOT NULL,
product_sprice int NOT NULL,
product_type varchar(50) NOT NULL,
product_supplier varchar(50) NOT NULL,
product_unit varchar (50) NOT NULL
)
INSERT INTO @tblproducts
SELECT 'ninja1', 'My Ninja product 1', '123', 'abc','GoGO', 100 UNION
SELECT 'ninja2', 'My Ninja product 2', '123', 'yyy','JO JO', 200 UNION
SELECT 'ninja3', 'My Ninja product 3', '222', 'xxx','XX JO', 111
DECLARE @tblorder TABLE (
order_id int NOT NULL IDENTITY(1,1) PRIMARY KEY,
order_qty int NOT NULL,
order_date varchar(100) NOT NULL,
product_code varchar(50)
)
DECLARE @tblstocks TABLE (
stocks_id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
stocks_qty int NOT NULL,
stocks_status varchar(50) NOT NULL,
stocks_date varchar(100) NOT NULL,
stocks_month varchar(100) NOT NULL,
stocks_year varchar(100) NOT NULL,
stocks_expiration varchar(100) NOT NULL,
product_barcode varchar(50) NOT NULL
)
INSERT INTO @tblstocks
SELECT 100,'STOCK IN', '1/1/2018','Jan',2018,'1/1/2099','ninja1' UNION
SELECT 40,'STOCK IN', '2/1/2018','Jan',2018,'1/1/2099','ninja2' UNION
SELECT 30,'STOCK IN', '3/1/2018','Feb',2018,'1/1/2099','ninja1' UNION
SELECT 50,'STOCK IN', '3/1/2018','Feb',2018,'1/1/2099','ninja3' UNION
SELECT 50,'STOCK OUT', '3/1/2018','Feb',2018,'1/1/2099','ninja1'
INSERT INTO @tblorder
SELECT 5,'1/3/2018','ninja1' UNION
SELECT 35,'2/3/2018','ninja1' UNION
SELECT 15,'2/3/2018','ninja2' UNION
SELECT 15,'3/3/2018','ninja2'
;WITH cteSumStocks AS (
SELECT product_barcode, SUM(stocks_qty) 'TotalStock' FROM @tblstocks WHERE stocks_status='STOCK IN'
GROUP BY product_barcode
)
, cteSumOrders AS (
SELECT product_code, SUM(order_qty) 'TotalOrder' FROM @tblorder
GROUP BY product_code
) SELECT s.product_barcode, p.product_name, s.TotalStock, o.TotalOrder, s.TotalStock - o.TotalOrder 'AvailableStocks'
FROM cteSumStocks s
JOIN cteSumOrders o
ON s.product_barcode = o.product_code
JOIN @tblproducts p
ON s.product_barcode = p.product_barcode
Output:
barcode name TotalStock TotalOrder AvailableStocks
ninja1 My Ninja product 1 130 40 90
ninja2 My Ninja product 2 40 30 10