Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 获取特定用户前后的用户及其排名_Mysql_Sql - Fatal编程技术网

Mysql 获取特定用户前后的用户及其排名

Mysql 获取特定用户前后的用户及其排名,mysql,sql,Mysql,Sql,我有一张这样的桌子: id|name|points 1|Ralph|15 2|Dave|2 3|Mourphy|180 我需要获得id为x的用户以及基于分数排名的前后5个用户: 我可以用 select *,rank() OVER (ORDER BY points DESC ) as rank from client where id = x; 如何重新审判其他人 谢谢一种方法是计算x的秩,并将其与每行的秩进行比较: select c.* from (select max(case when

我有一张这样的桌子:

id|name|points
1|Ralph|15
2|Dave|2
3|Mourphy|180
我需要获得id为x的用户以及基于分数排名的前后5个用户:

我可以用

select *,rank() OVER (ORDER BY points DESC ) as rank from client where id = x;
如何重新审判其他人


谢谢

一种方法是计算x的秩,并将其与每行的秩进行比较:

select c.*
from (select max(case when id = @x then rank end) over () as x_rank
      from (select c.*, rank() OVER (ORDER BY score DESC ) as rank 
            from client c
           ) c
     ) c
where rank >= x_rank - 5 and rank <= x_rank + 5;
请注意,如果您有关系,那么这可能不会精确返回11行

如果您想要前后正好5加上所有具有相同分数的行:

with c as (
      select max(case when id = @x then rank end) over () as x_rank
      from (select c.*, rank() OVER (ORDER BY score DESC ) as rank 
            from client c
           ) c
     )
(select c.*
 from c
 where rank < x_rank
 order by rank desc
 limit 5
) union all
(select c.*
 from c
 where rank = x_rank
) union all
(select c.*
 from c
 where rank > x_rank
 order by rank asc
 limit 5
) ;

你已经在问题中给出了答案。 这将是Sql Server风格

DECLARE @myRank int
SELECT @myRank = rank() OVER (Order BY points DESC) FROM client WHERE id = x;

Select *, rank() OVER (Order BY points DESC) as rank
FROM client 
HAVING rank between (@myRank - 5) and (@myRank +5);

如果您想在纯SQL中使用它,那么您需要做一些额外的工作,但在子查询中也是如此。

以表格式提供示例数据和预期输出为什么需要示例数据@fa06?似乎答案很直截了当。可能是直截了当可能不是-基于假设,你如何才能准确回答谢谢,我们可以使用秩函数执行此操作吗?@Zatla00。所有这些答案都使用秩函数。@LongChalk。第一个查询不是特别长。问题是它不处理领带。@LongChalk。我想你没抓住重点。这个问题的原始答案在你回答之前的很长一段时间内就发布了。此外,此答案解释了该答案的问题,并提供了解决方法。