0
我基础上,这个问题的答案查询:Handling ties when ranking from the highest to the lowest生产,Postgres的查询比本地SQLite查询返回不同的值
鉴于此数据集:
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
运行Postgres里在Heroku上完全相同的查询,我收到此错误:
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
感谢您的帮助!
完美!感谢tinychen! – 2010-08-03 03:03:11
+1令人敬畏的查询(ies)。十分优雅。 – 2010-08-03 11:56:33