Sum and Group by in Rails

匿名 (未验证) 提交于 2019-12-03 02:22:01

问题:

I have a table defined as such:

Name - Order# - Widget Count Bob  - 12311  - 6 Nancy- 12555  - 8 BoB  - 87573  - 12 Nancy- 12929  - 4 

I'd like to retrieve them as such:

Bob - 18 Nancy - 12 

Ie: A sum of their widget counts, ordered by name. I know how to go about this in SQL server/etc, but I'm not sure what the best practice is in Rails. Any help would be much appreciated!

回答1:

This should work, assuming your model is called Person:

Person.group(:name).count(:widget_count)

You can find more info about it on RailsGuides for ActiveRecord.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!