在排名之前和之后的特定用户之前吸引用户

时间:2019-03-13 11:00:39

标签: 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;

如何检索其他人?

谢谢

2 个答案:

答案 0 :(得分:1)

一种方法是计算“ 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行。

如果您想精确地在 plus 之前和之后的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
) ;

答案 1 :(得分:1)

您已经在问题内给出了答案。 它将是(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中使用它,则必须做一些额外的工作,但这是相同的想法(仅对于子查询而言)。