如果我像这样设置了两个单独的表:
University 1:
student major year gpa
University 2:
student major address gpa hometown extra curriculars
有什么方法可以让我的专业按该专业的最高gpa排序吗?抱歉,这可能是一个简单的问题,不过我对Ruby on Rails还是很新的。谢谢!
最佳答案
如果要获得两所大学的专业平均GPA最高的,则SQL看起来像这样,例如:
SELECT major, MAX(GPA) AS GPA FROM
(SELECT major, MAX(GPA) AS GPA FROM UNIVERSITY_1
GROUP BY major
UNION
SELECT major, MAX(GPA) AS GPA FROM UNIVERSITY_2
GROUP BY major)
GROUP BY major
ORDER BY GPA DESC
我不确定如何在Arel中表达该查询-不确定它如何进行联合,这很好知道。同时,您始终可以使用find_by_sql从原始SQL获取结果集。
编辑:
某种采用Ruby-er / Railsier的方式可能是:
u_one = UniversityOne.maximum :gpa, :group => 'major'
u_two = UniversityTwo.maximum :gpa, :group => 'major'
u_combined = u_one.merge(u_two) { |k, one, two| [one,two].max }
u_combined
最终是一个哈希,以主修科目为键,各大学的最大gpa为值。关于mysql - 表加入Ruby on Rails,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10409025/