title: SQL AVG of a SUM
body: <p>I want to get the <code>average</code> of a calculated <code>sum</code>. I have tried the syntax from <a href="https://stackoverflow.com/questions/1572831/avg-of-a-sum-in-one-query">this stackoverflow answer</a> So my SQL query looks like this:</p>
  
  <pre><code>SELECT AVG(iq.stockvalue_sum), iq.date
  FROM(
      SELECT CONCAT(DATE_FORMAT(s.date, '%Y'), '-01-01') as date,
      SUM(GREATEST(s.stockvalue,0)) as stockvalue_sum
      FROM stockvalues s
      GROUP BY CONCAT(DATE_FORMAT(s.date, '%Y'), '-01-01')
  ) iq
  </code></pre>
  
  <p>However this is not giving me a correct average. I want to get the average <code>stockvalue</code> for each year. The idea behind the table is to save every day the stock and stockvalue for each product. So this specifiq query is to show the average stockvalue for each year it has data for.</p>
  
  <p><strong>Edit:</strong> Sample output data</p>
  
  <pre><code>Stockvalue | Year
  _________________
  -  205     | 2015
  -  300     | 2014
  </code></pre>
  
  <p>Input data:</p>
  
  <pre><code>pid | val | date
  ______________________
  - 1 | 100 | 28-04-2015
  - 2 | 150 | 28-04-2015
  - 1 | 80  | 27-04-2015
  - 2 | 80  | 27-04-2015
  ....
  - 1 | 100  | 29-01-2014
  - 2 | 100  | 29-01-2014
  - 1 | 200  | 30-01-2014
  - 2 | 200  | 30-01-2014
  </code></pre>
  
  <p>So I need to calculate know the average of the <code>total</code> stockvalue. So the sum of all stockvalues for day X and the average of X</p>