聚合列上的 PostgreSQL RANK() 函数

Ján*_*čko 6 postgresql aggregate-functions rank

我正在构建相当复杂的查询,我尝试加载用户的聚合点及其排名。我发现 RANK() 函数可以帮助我实现这一目标,但无法让它工作。

以下是在没有 RANK 的情况下运行的查询:

SELECT users.*, SUM(received_points.count) AS pts 
FROM users 
LEFT JOIN received_points ON received_points.user_id = users.id AND ...other joining conditions... 
GROUP BY users.id 
ORDER BY pts DESC NULLS LAST
Run Code Online (Sandbox Code Playgroud)

现在我还想选择排名 - 但这种使用 RANK 函数的方式不起作用:

SELECT users.*, SUM(received_points.count) AS pts, 
    RANK() OVER (ORDER BY pts DESC NULLS LAST) AS position
FROM users 
LEFT JOIN received_points ON received_points.user_id = users.id AND ...other joining conditions... 
GROUP BY users.id 
ORDER BY pts DESC NULLS LAST
Run Code Online (Sandbox Code Playgroud)

它说:PG::UndefinedColumn: ERROR: column "pts" does not exist

我想我对窗口函数的整个概念都是错误的。如何选择按聚合值排序的用户排名,如上pts例所示?

我知道我可以在之后手动分配排名,但是如果我还想根据查询中的 users.name 过滤行,并且仍然获得用户在一般(未过滤)排行榜中的排名...?不知道我说清楚了没有...

Ján*_*čko 2

正如马斯在他的评论中所建议的:

您不能pts在此处使用,因为别名尚不存在(您不能以SELECT定义的方式引用别名)。RANK() OVER (ORDER BY SUM(received_points.count) DESC NULLS LAST)应该可以正常工作。