title: SQL Server: join two tables using loop
body: <p>I have two tables. I am new to T-SQL. </p>
  
  <p>First select returns this result:</p>
  
  <pre><code>ID  Quantity
  -------------
  1      30
  2      25
  </code></pre>
  
  <p>Second select returns this result:</p>
  
  <pre><code>ID    Document   QuantityS    Date
  ----------------------------------------
   1    DocA          12        22-03-2017
   1    DocB          10        18-03-2017
   1    DocC          10        15-03-2017
   1    DocD           8         6-03-2017
   2    DocA          20        21-04-2017
   2    DocB          12        18-04-2017
   2    DocC          10        13-04-2017
  </code></pre>
  
  <p>I need to join this two table on ID and get rows from second table while sum of <code>quantityS</code> is bigger or equal to the <code>Quantity</code> from the first table, ordered by <code>Date desc</code>.</p>
  
  <p>I need to get table like this:</p>
  
  <pre><code>ID    Document    QuantityS     Date
  ------------------------------------------
   1    DocA           12         22-03-2017
   1    DocB           10         18-03-2017
   1    DocC           10         15-03-2017
   2    DocA           20         21-04-2017
   2    DocB           12         18-04-2017
  </code></pre>
  
  <p>I don't need the last row from second table because the sum of quantity from three row is 32 which is bigger than 30.</p>
  
  <p>Any ideas?</p>