我的数据看起来像这样
___________________________________
|name date status location |
|Tom 1/1/2010 Ready Home |
|Tom 1/1/2010 Ready Home |
|Bill 1/18/2010 Go Work |
|Bob 2/19/2010 Ready Field |
|Bob 2/19/2010 Ready Field |
|Wil 4/5/2010 Steady Work |
|Wil 4/5/2010 Steady Work |
|Wil 4/5/2010 Steady Work |
|Wil 4/5/2010 Steady Home |
|Bill 7/14/2010 Stop Home |
|___________________________________|
我需要对它进行分组/计数,使其看起来像这样
Name Date Location Status Count
Tom 1/1/2010 Home Ready 2
Bill 1/18/2010 Work Go 1
Bill 7/14/2010 Home Stop 1
Bob 2/19/2010 Field Ready 2
etc.....
答案 0 :(得分:2)
根据数据的格式和属性,有时最好的方法是棘手的。但一般来说,您可以使用ActiveRecord#find的:group
参数。
Model.all(:select => 'COUNT(*) AS count, name, date, location, status', :group => 'name')
或者如果使用Rails 3
Model.all.select('COUNT(*) AS count, name, date, location, status').group('name')
如果您始终打算根据此关系对数据进行分组,请考虑将其作为默认范围添加到模型中。
class Model < ActiveRecord::Base
default_scope select('COUNT(*) AS count, name, date, location, status')
default_scope group('name')
end