i'm trying to do LEFT JOIN with SUM 2 of 4 tables, and i'm stuck
In the expected result in the bottom below, there is new field called begin_stock
and end_stock
result of daily_stock.qty
which is filtered by dates_stat
but does not need to use sum()
because the values is final.
You can try in in here: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=07defd60df696a8717fc8e3096592545
Heres the tables:
product
:
id product_name
1 abc
2 aaa
3 bbb
4 ddd
usage
: need to use sum()
id product_id used date_out
1 1 10 2020-12-18
2 1 20 2020-12-19
3 2 20 2020-12-18
product_restock
: need to use sum()
id product_id restock_amount date_in
1 1 10 2020-12-18
2 1 20 2020-12-19
3 4 10 2020-12-19
daily_stock
id product_id qty dates_stat
1 1 10 2020-12-18
2 2 10 2020-12-18
3 3 10 2020-12-18
4 4 10 2020-12-18
5 1 10 2020-12-19
6 2 -10 2020-12-19
7 3 10 2020-12-19
8 4 20 2020-12-19
Expected result from date 2020-12-18
to 2020-12-19
:
id product_name begin_stock restock used end_stock
------ ------------ ------------- ------- ---- -------------
1 abc 10 30 30 10
2 aaa 10 0 20 -10
3 bbb 10 0 0 10
4 ddd 10 10 0 20