我构建了相当复杂的查询,我试图用他们的排名加载用户的聚合点。我发现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
现在我想选择排名 - 但这种方式使用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
它告诉:PG::UndefinedColumn: ERROR: column "pts" does not exist
我想我得到了窗口函数的整个概念错误。如何选择按上面示例中的pts
等聚合值排序的用户排名?
我知道我之后可以手动分配排名,但是如果我还想根据查询中的users.name过滤行,并且仍然可以获得用户的排名(未过滤)排行榜。 。?不知道我是否清楚......