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 过滤行,并且仍然获得用户在一般(未过滤)排行榜中的排名...?不知道我说清楚了没有...