This should be easy. In MySQL I could just do:
select sum(column1*column2) as sum1 from table
How do you do this in Rails with sqlite? I've tried find_by_sql with the exact query above, as well as find(:all, :select=>...), and all sorts of other things, but none return the proper value. Most are just blank, like this:
[#<Element> ]
I could loop through, pull out values, and then sum, but it seems absurd to have to do that.
Can someone point me to what I'm obviously 开发者_如何学编程missing? Thanks!
http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html
As @glortho said in a comment, the solution is
Element.sum( "column1*column2" )
This even works across multiple tables
Foo.includes(:bars).references(:bars).sum('foos.cost * bars.available')
SQL IS INCREDIBLE!
精彩评论