title: PostgreSQL Left Join with SUM 2 of 4 Table
body: <p>i'm trying to do LEFT JOIN with SUM 2 of 4 tables, and i'm stuck</p>
  <p>In the expected result in the bottom below, there is new field called <code>begin_stock</code> and  <code>end_stock</code>result of <code>daily_stock.qty</code> which is filtered by <code>dates_stat</code> but does not need to use <code>sum()</code> because the values is final.</p>
  <p>You can try in in here: <a href="https://dbfiddle.uk/?rdbms=postgres_12&amp;fiddle=07defd60df696a8717fc8e3096592545" rel="nofollow noreferrer">https://dbfiddle.uk/?rdbms=postgres_12&amp;fiddle=07defd60df696a8717fc8e3096592545</a></p>
  <p>Heres the tables:</p>
  <p><code>product</code>:</p>
  <pre><code>id  product_name 
  1   abc            
  2   aaa            
  3   bbb             
  4   ddd             
  </code></pre>
  <p><code>usage</code>: need to use sum()</p>
  <pre><code>
  id  product_id  used    date_out
  1   1           10      2020-12-18
  2   1           20      2020-12-19
  3   2           20      2020-12-18
  </code></pre>
  <p><code>product_restock</code>: need to use sum()</p>
  <pre><code>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
  </code></pre>
  <p><code>daily_stock</code></p>
  <pre><code>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
  </code></pre>
  <p><strong>Expected result</strong> from date <code>2020-12-18</code> to <code>2020-12-19</code>:</p>
  <pre><code>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
  </code></pre>