PostgreSQL:同一个表中每个项目的前n个条目

时间:2011-09-30 17:13:41

标签: sql postgresql greatest-n-per-group

| 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

等...

我尝试每makers只检索3条记录,前3条amountswidgets生成

这就是我所拥有的:

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;

这是否归还了我真正需要的东西?有没有更好的方法来解决这个问题?我所看到的大多数方法都是在不同的表上进行连接等,我需要的所有信息都放在一张桌子上。

预期产出:

| 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

等...

makers的顺序与获得每个amounts的前三名makers以及他们提供的widgets无关。已设置makers的数量,始终为x makers

1 个答案:

答案 0 :(得分:14)

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