title: PostgreSQL: top n entries per item in same table
body: <pre><code>| uId |   title   |  amount  |  makers  |  widgets  |
     1     richard      998       xcorp     sprocket
     2     swiss        995       ycorp     framitz
     3     ricky         90       zcorp     flobber
     4     ricky2       798       xcorp     framitz
     1     lilrick      390       xcorp     sprocket
     1     brie         200       mcorp     gullywok
     1     richard      190       rcorp     flumitz
     1     brie         490       bcorp     sprocket
  </code></pre>
  
  <p>etc...</p>
  
  <p>I am trying to retrieve only 3 records per <code>makers</code>, the top 3 <code>amounts</code> and the <code>widgets</code> they produced</p>
  
  <p>Here's is what I have:</p>
  
  <pre><code>SELECT amount, makers FROM (SELECT amount, makers, (SELECT count(*) FROM  entry  as t2
  WHERE t2.amount = t1.amount and t2.makers &gt;= t1.makers) AS RowNum
  FROM entry as t1
  ) t3
  WHERE t3.RowNum&lt;4 order by amount;
  </code></pre>
  
  <p>Is this returning what I actually need? Is there a better way to go about this? Most of the ways I have seen to do this kind of thing are doing joins etc on disparate tables, all the info I need is on one table.</p>
  
  <p>Expected Output:</p>
  
  <pre><code>| uId |   title   |  amounts  |  makers  |  widgets  |
    1      richard      998        xcorp     sprocket
    41     swiss        995        xcorp     widget
    989    richard      989        xcorp     sprocket
    22     swiss        995        ycorp     framitz
    92     swiss        990        ycorp     widget
    456    swiss        895        ycorp     flobber
    344    ricky        490        zcorp     flobber
    32     tricky       480        zcorp     flobber
    13     ricky        470        zcorp     flobber
  </code></pre>
  
  <p>etc...</p>
  
  <p>The order of the <code>makers</code> doesn't matter so much as getting the top 3 <code>amounts</code> for each <code>makers</code>, and the <code>widgets</code> they provided. The number of <code>makers</code> is set, there will always be <code>x</code> <code>makers</code></p>