I have a query based on the answer to this question: http://stackoverflow.com/questions/2939061/handling-ties-when-ranking-from-the-highest-to-the-lowest/2939079#2939079
Given this dataset:
Name | Score
Mike | 5
John | 3
Mary | 3
Matt | 0
The following query returns a user array containing the correct values.
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
Running the exact same query in Postgres on Heroku, I receive this error:
ActiveRecord::StatementInvalid: PGError: ERROR: more than one row returned by a subquery used as an expression
Adding a LIMIT 1
on the inner select results in the following funky data:
Name | Score | Rank
Mike | 5 | nil
John | 3 | 2
Mary | 3 | 2
Matt | 0 | 2
Thanks for the help!