2010-08-03 63 views
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

感谢您的帮助!

回答

1

。在你的SQL.Change它这样一些问题:

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 

我已经尝试过了没有没有问题您也可以尝试这个statement.They有同样的结果。

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 
+0

完美!感谢tinychen! – 2010-08-03 03:03:11

+0

+1令人敬畏的查询(ies)。十分优雅。 – 2010-08-03 11:56:33