title: accumulated sum in query
body: <p>How is it possible to return rows with an accumulate sum for a row bigger or smaller than a specified value?</p>
  
  <h1>table:</h1>
  
  <pre><code>id | count
  -----------
  1 | 30
  2 | 10
  3 | 5
  4 | 20
  5 | 15
  </code></pre>
  
  <h1>query:</h1>
  
  <pre><code>SELECT id, count
  FROM table
  ORDER BY id
  HAVING SUM(count) &lt; 50
  </code></pre>
  
  <h1>return rows:</h1>
  
  <pre><code>id | count
  -------------
  1 | 30
  2 | 10
  3 | 5
  </code></pre>
  
  <h1>update</h1>
  
  <p>code:</p>
  
  <pre><code>public function query(){
      switch($this-&gt;table){
          case 'in_stock':
              return "SELECT * FROM ".Init::$static['db'].".stock
                  WHERE id&lt;=dynaccount.stock_first_available_id(".$this-&gt;value['num_stock'].", ".$this-&gt;value['product_id'].", ".(isset($this-&gt;att_arr['gid']) ? $this-&gt;att_arr['gid']:$_SESSION['gid']).")
                  ORDER BY time, id";
      }
  }
  </code></pre>
  
  <p>procedure:</p>
  
  <pre><code>DELIMITER $$
  
  DROP FUNCTION IF EXISTS `stock_first_available_id` $$
  CREATE DEFINER=`dynaccount`@`localhost` FUNCTION `stock_first_available_id`(_running_total_limit INT, _product_id INT, _group_id INT) RETURNS INT
  BEGIN
      DECLARE _running_count INT default 0;
      DECLARE _id INT;
      DECLARE _current_id INT;
      DECLARE _sum_count INT;
  
      IF (SELECT COUNT(*) FROM stock WHERE group_id=_group_id &amp;&amp; type=2 &amp;&amp; product_id=_product_id) = 0 THEN
          RETURN 0;
      END IF;
  
      DECLARE _cur CURSOR FOR SELECT id, count FROM stock WHERE group_id=_group_id &amp;&amp; type=2 &amp;&amp; product_id=_product_id ORDER BY time DESC, id DESC;
  
      OPEN _cur;
  
      read_loop: LOOP
          FETCH _cur INTO _id, _sum_count;
  
          SET _running_count = _running_count + _sum_count;
          SET _current_id = _id;
  
          IF _running_count &gt; _running_total_limit THEN
              LEAVE read_loop;
          END IF;
      END LOOP read_loop;
  
      CLOSE _cur;
  
      RETURN _current_id;
  END $$
  
  DELIMITER ;
  </code></pre>
  
  <p>error:</p>
  
  <pre><code>#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE _cur CURSOR FOR SELECT id, count FROM stock WHERE group_id=_group_id &amp;amp;&amp;amp; ' at line 12 
  </code></pre>