小编典典

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

sql

| 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

等等…

我正在尝试仅检索3条记录makers,前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每个的前3名makerswidgets就可以了。makers设置的数量,总会有x``makers


阅读 162

收藏
2021-03-10

共1个答案

小编典典

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

2021-03-10