Rails 中相乘列的总和

glo*_*tho 5 sql select sum ruby-on-rails

这应该很容易。在 MySQL 中我可以这样做:

select sum(column1*column2) as sum1 from table
Run Code Online (Sandbox Code Playgroud)

如何在 Rails 中使用 sqlite 执行此操作?我已经尝试使用 find_by_sql 与上面的确切查询,以及 find(:all, :select=>...) 和各种其他东西,但没有一个返回正确的值。大多数都是空白的,像这样:

[#<Element> ]
Run Code Online (Sandbox Code Playgroud)

我可以循环遍历,取出值,然后求和,但必须这样做似乎很荒谬。

有人能指出我明显缺少的东西吗?谢谢!

Ena*_*ane 2

http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html

  • 没关系。Element.sum(“column1*column2”) 有效。只是从来没有找到相关模型和列的正确组合。谢谢! (3认同)