Sum multiple columns individually

Can you sum a few columns at a time?

I tried
x =Calc.find(:all, :select => “sum(amt1) amt1, sum(amt2) amt2”
:conditions => [“where date > ?”, date] )

The sql seems to function properly, but I wasn’t able to grab the
values. These just failed

x.amt1
x.send(“amt1”)

I tried changing up the query to use

sum(amt1) as amt1
sum(amt1) ‘amt1’
sum(amt1) as ‘amt1’

but none worked.

undefined method `amt1’ for [#<;Calc:0x2ac605ec9508
@attributes={“amt1”=>2.0, “amt2”=>2.0}>}>]:Array

the “amt”=> 2 are correct, but I just cant seem to access the value

On 1/25/07, Alex T. [email protected] wrote:

x.amt1
x.send(“amt1”)

You’re getting back an array. Try x[0].amt1 for example.

JDL wrote:

You’re getting back an array. Try x[0].amt1 for example.

That did it. I thought it was a little odd that I had to do
x[0].amt2 as well, but I suppose the array is the first thing returned
then I’m going after each element.

Thanks for the help!

Alex

On 1/25/07, Alex T. [email protected] wrote:

JDL wrote:

You’re getting back an array. Try x[0].amt1 for example.

That did it. I thought it was a little odd that I had to do
x[0].amt2 as well, but I suppose the array is the first thing returned
then I’m going after each element.

Thanks for the help!

Using find(:first) or find(:all) is incorrect here since technically
you’re not retrieving a model. You’re retrieving aggregated data from
the db. It’d be nice to add support for multiple values to
ActiveRecord::Calculations, but I can’t envision a decent API that
doesn’t look hackish. Your best bet is to use connection.select_all
or select_values

returns array of values, like [1, 5]

def sum_amounts
connection.select_values(“SELECT sum(amt1), sum(amt2) …”)
end

or…

select_all returns an array, but since it’s an aggregation, it

should only return 1 row.

Calling #first returns a hash like { ‘amt1’ => 1, ‘amt2’ => 5 }

def sum_amounts
connection.select_all(“SELECT sum(amt1), sum(amt2) …”).first
end

Rick O.
http://weblog.techno-weenie.net
http://mephistoblog.com