使用:Rails 2.3.8 ruby 1.8.7
如何将以下查询转换为Rails(Active-Record)
SELECT distinct source_code, count(source_code)
FROM table
GROUP BY 1
返回=>
| source_code | count |
| ABC | 16 |
| XYZ | 2 |
Model.find(:all, :select => "distinct source_code, count(source_code)",
:group => 1)
=> [Model source_code: "ABC">, Model source_code: "XYZ">]
如您所见,结果集中缺少计数。
答案 0 :(得分:2)
您的SQL语句不需要DISTINCT
子句,因为GROUP BY
子句将返回不同的sourcecode
行。
在rails 2.3.x中,您可以获得如下所需的结果:
Model.count(:group => :source_code)
# returns an ordered hash
{
"ABC" => 16,
"XYZ" => 2
}