select 排名和计数

select rank and count

我有 table 的用户个人资料,我正在尝试根据他们的 exp 在系统中获取用户的个人资料及其 rank 有多少用户。我的目标是最终打印出这个用户说...“在服务器上 135 人中排名 5th”。我可以获得 rank(),但无法弄清楚如何获得 max(rank()) 或只是一个 count(),因为它需要 group by,但通过分组我是不允许变得有意义 count()。 这是我尝试过的:

select profile_ranked.*, max(profile_ranked.rank)
from (
    select
           *,
           rank() over (order by exp desc, id desc) as rank
    from profile
    where server_id = 6410
    ) as profile_ranked
where user_id = 1003

这会抛出错误,说需要 gouping,这最终使目标失败。 我试过的另一件事。这次 count():

select profile_ranked.*
from (
    select
           *,
           rank() over (order by exp desc, id desc) as rank,
           count(*) as count
    from profile
    where server_id = 6410
    group by id
    ) as profile_ranked
where user_id = 1003

count 列中的输出始终为 1,因为我不得不按 id 进行分组。否则代码甚至不执行,抛出错误。

我可以做 2 个查询,遍历 table 两次,是的,但是这样做没有意义,如果我需要做的只是获得 rank() 的结果,并且max()。所以我正在寻找一种更优雅的方式来解决这个问题。 基本上,我知道我需要将 count()max() 的相同值附加到每一行。那会解决问题。但我不知道该怎么做。我们将不胜感激。

您想要在子查询中使用 window 计数:

select *
from (
    select p.*,
        rank() over (order by exp desc, id desc) as rn,
        count(*) over() as cnt
    from profile
    where server_id = 6410
) as p
where user_id = 1003