我根据这个问题的答案进行了查询:Handling ties when ranking from the highest to the lowest
鉴于此数据集:
Name | Score
Mike | 5
John | 3
Mary | 3
Matt | 0
以下查询返回包含正确值的用户数组。
User.find_by_sql("SELECT id, score, (SELECT COUNT(DISTINCT outertable.score) + 1
FROM users WHERE score > outertable.score ORDER BY score ASC) AS rank
FROM users as outertable GROUP BY outertable.id, outertable.score
ORDER BY score DESC LIMIT 30")
Name | Score | Rank
Mike | 5 | 1
John | 3 | 2
Mary | 3 | 2
Matt | 0 | 3
在Heroku上的Postgres中运行完全相同的查询,我收到此错误:
ActiveRecord::StatementInvalid: PGError: ERROR: more than one row returned by a subquery used as an expression
在内部选择中添加LIMIT 1
会产生以下时髦数据:
Name | Score | Rank
Mike | 5 | nil
John | 3 | 2
Mary | 3 | 2
Matt | 0 | 2
感谢您的帮助!
答案 0 :(得分:1)
您的SQL存在一些问题。请将其改为:
SELECT name,score,
(SELECT COUNT(DISTINCT score) + 1
FROM users WHERE score > outertable.score
) AS rank
FROM users as outertable
GROUP BY outertable.name, outertable.score
ORDER BY score DESC LIMIT 30
我已经尝试过没有任何问题!你也可以试试这句话。他们也有同样的结果。
select a.name,
a.score,
count(distinct b.score)+1 as rank
from
users a left join users b
on a.score > b.score
group by
a.name,a.score
order by a.score desc limit 30