具有独特的GROUP BY和用于活动记录的计数(Rails)

时间:2012-02-13 18:40:30

标签: mysql ruby-on-rails activerecord

使用:Rails 2.3.8 ruby​​ 1.8.7

如何将以下查询转换为Rails(Active-Record)

MYSQL

SELECT distinct source_code, count(source_code)
FROM table
GROUP BY 1

返回=>

| source_code | count |
| ABC         | 16    |
| XYZ         | 2     |

Rails Attempt

Model.find(:all, :select => "distinct source_code, count(source_code)", 
                 :group => 1)

=> [Model source_code: "ABC">, Model source_code: "XYZ">]

如您所见,结果集中缺少计数。

1 个答案:

答案 0 :(得分:2)

您的SQL语句不需要DISTINCT子句,因为GROUP BY子句将返回不同的sourcecode行。

在rails 2.3.x中,您可以获得如下所需的结果:

Model.count(:group => :source_code)

# returns an ordered hash
{
  "ABC" => 16,
  "XYZ" => 2
}