SQL rails 按多列分组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1241352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
rails group by multiple columns
提问by philipth
i have budgets table with emptype_id and calendar_id actual_head, estimated_head
我有一个带有 emptype_id 和 calendar_id actual_head、estimated_head 的预算表
when i do Budgets.sum(:actual_head ,:group=>"emptype_id,calendar_id")
i do not get the result grouped by the above two columns but only by the emptype_id
当我这样Budgets.sum(:actual_head ,:group=>"emptype_id,calendar_id")
做时,我 没有得到按上述两列分组的结果,而只是按emptype_id
however when i check the log the sql query is right
但是,当我检查日志时,sql 查询是正确的
SELECT sum(`budgets`.actual_head) AS sum_actual_head, emptype_id,calendar_id AS emptype_id_calendar_id FROM `budgets` GROUP BY emptype_id,calendar_id
has 103 rows
有 103 行
I wanted to iterate through each emptype_id and calendar_id to get a sum of actual_head and do some calculations on it.
我想遍历每个 emptype_id 和 calendar_id 以获得 actual_head 的总和并对其进行一些计算。
回答by Lawrence Pit
Grouping with multiple columns cannot be supported by rails. You have to use a regular find all:
rails 不支持多列分组。您必须使用常规查找全部:
budgets = Budgets.find(:all,
:select => "emptype_id, calendar_id, sum(budgets.actual_head) AS sum_actual_head",
:group => "emptype_id, calendar_id")
budgets.each { |budget| puts budget.sum_actual_head }
回答by Ben
I cheat. Do :group => ["emptype_id,calendar_id"].
我作弊。做:group => ["emptype_id,calendar_id"].
Not want you nor I want, but this works at least.
不想要你也不想要,但这至少有效。
回答by Matt Grande
I'm not sure of this, buy try :group => [:emptype_id, :calendar_id]
这个我不确定,买试试 :group => [:emptype_id, :calendar_id]