i'm trying to do LEFT JOIN with SUM and Arithmetic Operators of 3 tables, and i'm stuck,
In the expected result in the bottom below, there is new field called initial_stock
which is the result of:
initial_stock
= current_stock
+ sum(used)
- sum(restock_amount)
You can try in in here: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=2216e64ee6fa90556d8f952f115dd070
Heres the tables:
product
table:
id product_name current_stock
------ ------------ -------------
1 abc 10
2 aaa 0
3 bbb 10
4 ddd 20
usage
table:
id product_id used date_out
------ ------------ ------- ----------
1 1 10 2020-11-20
2 1 20 2020-11-20
3 2 20 2020-11-11
product_restock
table:
id product_id restock_amount date_in
------ ------------ -------------- -----------
1 1 10 2020-11-15
2 1 20 2020-11-14
3 4 10 2020-11-09
Expected result from date 2020-11-01
to 2020-11-30
:
id product_name initial_stock restock used current_stock
------ ------------ ------------- ------- ---- -------------
1 abc 10 30 30 10
2 aaa 20 0 20 0
3 bbb 10 0 0 10
4 ddd 10 10 0 20