glortho
glortho

Reputation: 13200

Sum of multiplied columns in Rails

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!

Upvotes: 5

Views: 4042

Answers (2)

hrdwdmrbl
hrdwdmrbl

Reputation: 5279

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!

Upvotes: 2

Related Questions