首页 > 解决方案 > 使用用户详细信息 SQL 查找排名

问题描述

我正在为我的 SQL 技能而苦苦挣扎。我正在尝试获取表中用户的排名,我使用在 stackoverflow 中找到的以下查询,它运行良好。

Select count(brp.*) + 1 From run_progress brp, (SELECT * FROM run_progress WHERE runner = 1 ) p WHERE brp.progress > p.progress;

它给了我正确的等级,但我也想获得'p' p 的详细信息,详细信息有等级人员的详细信息。我怎样才能做到这一点 ?希望我的问题很清楚。需要选择“p”的所有列。

谢谢你

更新

CREATE TABLE run_progress
(
   id INT PRIMARY KEY,
   user varchar(255),
   progress numeric
)

INSERT INTO run_progress ( id, user, progress ) VALUES ( 9, 1, 100 )
INSERT INTO run_progress ( id, user, progress ) VALUES ( 11, 2, 90 )
INSERT INTO run_progress ( id, user, progress ) VALUES ( 14, 3, 60 )
INSERT INTO run_progress ( id, user, progress ) VALUES ( 10, 4, 10 )

这是我的桌子

for user:1 it should give me - 1, 9,1,100
for user:4 it should give me - 4, 10,4,100

希望那很清楚。

标签: sqlpostgresql

解决方案


你为什么不使用窗口函数?这些性能更好,功能更强大:

select brp.*
from (SELECT brp.*, ROW_NUMBER() OVER (ORDER BY progress DESC) as seqnum
      FROM runprogress brp
     ) brp

我不是 100% 确定你想要什么,但是如果你想要 的排名runner = 1,那么添加一个where子句:

select brp.*
from (SELECT brp.*, ROW_NUMBER() OVER (ORDER BY progress DESC) as seqnum
      FROM runprogress brp
     ) brp
where runner = 1;

注意:您的排名方法为跑步者提供了相同的progress不同排名,这就是为什么使用ROW_NUMBER(). 如果您希望平局得分相同,请使用RANK()DENSE_RANK()

是一个 db<>fiddle。


推荐阅读