Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL: top n entries per item in same table

| 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

etc...

I am trying to retrieve only 3 records per makers, the top 3 amounts and the widgets they produced

Here's is what I have:

SELECT amount, makers FROM (SELECT amount, makers, (SELECT count(*) FROM  entry  as t2
WHERE t2.amount = t1.amount and t2.makers >= t1.makers) AS RowNum
FROM entry as t1
) t3
WHERE t3.RowNum<4 order by amount;

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.

Expected Output:

| 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

etc...

The order of the makers doesn't matter so much as getting the top 3 amounts for each makers, and the widgets they provided. The number of makers is set, there will always be x makers

like image 420
roberthuttinger Avatar asked Sep 30 '11 17:09

roberthuttinger


1 Answers

SELECT *
FROM (
   SELECT uid,
          title, 
          amount, 
          maker, 
          widgets,
          rank() over (partition by maker order by amount desc) as rank
   FROM entry  
) t
WHERE rank <= 3
like image 69
a_horse_with_no_name Avatar answered Oct 24 '22 15:10

a_horse_with_no_name