I have three tables, products
,stock or inwards
,loading or outwards
so i want to to have sql query which will calculate the Closed balance from this Formular in date range
Closed balance= Open balance+inward-outward
For Example
products table
Id ProductName OpenStock
1 Item 1 500
2 Item 1 40
3 Item 1 700
4 Item 1 80
Stock table(assume no stock in)
id pid qty Indate
1 1 0 2020-04-28
2 2 0 2020-04-28
3 3 0 2020-04-28
Loading table
id pid qty Outdate
1 1 30 2020-04-28
2 2 50 2020-04-28
3 3 30 2020-04-28
Am expecting that today Stock summary will be like this
Pid OB inward outward CB
1 500 0 30 470
2 400 0 50 350
3 700 0 30 670
....
So tomorrow (next date) We expect that if there is no Inward or Ourwards quantity stock summary will be and so on:
Pid OB inward outward CB
1 470 0 30 470
2 350 0 50 350
3 670 0 30 670
What can i archive this stock summary
, by sql query and what if i want to select from date to date
this is my sql query which return the screenshot below but does not works correct
public function searchstockview(Request $request) {
request()->validate([
'startdate' =>'required',
'enddate' => 'required',
]);
$startdate=$request->startdate;
$enddate=$request->enddate;
$viewstockbydate= DB::select(DB::raw(" SELECT
products.id,
products.name,products.open_stock as open_balance,
(select ifnull(sum(loadings.qty),0) from loadings where loadings.pid=products.id and
DATE(loadings.created_at) BETWEEN STR_TO_DATE('$startdate','%m/%d/%Y') AND
STR_TO_DATE('$enddate','%m/%d/%Y') ) as total_loadings_specific_date,
(select categories.name from categories where categories.id=products.category_id) as
category_name,
(select ifnull(sum(stocks.qty),0) from stocks where stocks.pid=products.id and
DATE(stocks.created_at) BETWEEN STR_TO_DATE('$startdate','%m/%d/%Y') AND
STR_TO_DATE('$enddate','%m/%d/%Y') ) as total_stocks_specific_date
from products"));
}
keep in mind that is this query i takes open_balance
,total_loadings_specific_date
,total_stocks_specific_date
and put in the formular above to get closed balance but this logic is not correct i need new ideas. how to resolve this