title: Limit amount of rows used by average
body: <p>I've a query (postgresql) where I'd like to limit the rows used for computing the average </p>
  
  <pre><code>SELECT username,avg(income),count(*) FROM
         Events 
  WHERE to_timestamp(eventtimestamp)  &gt;=  '2008-02-23' AND 
        to_timestamp(eventtimestamp) &lt;=   '2009-01-03' and username='Joe'
  GROUP BY userid 
  </code></pre>
  
  <p>Joe has 40 entries but I want to limit the amount of rows used to compute the average of his income. I'm aware of the <strong>limit</strong> function I could add at the end of the query but this limits the output of the <em>whole</em> query instead of the rows considered by the <strong>average</strong> command in the head of the query. Any hints how I could tell avg to use only first n rows?</p>
  
  <p>e.g. <strong>not working</strong></p>
  
  <pre><code>SELECT username,avg(income) limit 5,count(*) FROM
         Events 
  WHERE to_timestamp(eventtimestamp)  &gt;=  '2008-02-23' AND 
        to_timestamp(eventtimestamp) &lt;=   '2009-01-03' and username='Joe'
  GROUP BY userid 
  </code></pre>
  
  <p>to average only over the first 5 rows.</p>
  
  <p>Thanks!</p>