gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 11:26:13 25 4
gpt4 key购买 nike

| 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 个 amounts 和他们生产的 widgets

这是我所拥有的:

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 的顺序并不重要,重要的是为每个 makers 获得前 3 个 amount,而 他们提供的小部件maker的数量是固定的,总会有x maker

最佳答案

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

关于sql - PostgreSQL:同一表中每个项目的前 n 个条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7613785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com