sql - 使用用户详细信息 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
希望那很清楚。
解决方案
你为什么不使用窗口函数?这些性能更好,功能更强大:
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。
推荐阅读
- javascript - 如何在 Angular 6 中生成条形码?
- php - 无法在同一页面上回显行 mysql 数据
- c++ - Boost超几何测试
- java - 尝试访问 pojo 时出现 NoMessageBodyWriterFoundFailure
- azure - Azure - 带有正则表达式的 Web API 和路由模板
- python - 如何手动安装 Numpy (Linux)?
- css - CSS Grid 将主页分成两部分
- docker - traefik docker 标签中基于主机和路径的路由规则的混合
- html - 如何根据悬停效果设置背景颜色,即当鼠标悬停在为类的背景颜色定义的相同 css 定义中的 li 项目上时?
- python - 对一个列表进行排序以使两个列表具有正确的顺序对应关系