title: Calculating a Moving Average MySQL?
body: <p>Good Day,</p>
  
  <p>I am using the following code to calculate the 9 Day Moving average.</p>
  
  <pre><code>SELECT SUM(close)
  FROM tbl
  WHERE date &lt;= '2002-07-05'
  AND name_id = 2
  ORDER BY date DESC
  LIMIT 9
  </code></pre>
  
  <p>But it does not work because it first calculates all of the returned fields before the limit is called. In other words it will calculate all the closes before or equal to that date, and not just the last 9.</p>
  
  <p>So I need to calculate the SUM from the returned select, rather than calculate it straight.</p>
  
  <p>IE. Select the SUM from the SELECT...</p>
  
  <p>Now how would I go about doing this and is it very costly or is there a better way? </p>