title: Group only top n rows in sql
body: <p>I have a table (myTab), which has 3 columns(id, marketValue, stock).</p>
  
  <p>I want to group top n rows ordered by marketValue. I can think of this nested query.</p>
  
  <pre><code>SELECT AVG(marketValue), stock FROM (SELECT marketValue, stock FROM myTab
  order by(marketValue) desc LIMIT(n)) GROUP BY stock. 
  </code></pre>
  
  <p>Can we optimise it further? This is <em>not</em> to get top n rows of <em>each</em> group.</p>
  
  <p>SAMPLE TABLE</p>
  
  <p><a href="https://i.stack.imgur.com/aSIrM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aSIrM.png" alt="enter image description here"></a></p>
  
  <p>If I group top 3 rows, the expected result should be :</p>
  
  <p><a href="https://i.stack.imgur.com/P0GxU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/P0GxU.png" alt="enter image description here"></a></p>