# Doing a SQL sum and getting the result into rails

**URL:** <https://www.ruby-forum.com/t/doing-a-sql-sum-and-getting-the-result-into-rails/92522>\
**Category:** Rails\
**Created:** [April 20, 2007, 9:19am UTC](https://www.ruby-forum.com/t/doing-a-sql-sum-and-getting-the-result-into-rails/92522 "2007-04-20T09:19:55Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 20, 2007, 9:19am UTC](https://www.ruby-forum.com/t/doing-a-sql-sum-and-getting-the-result-into-rails/92522/1 "2007-04-20T09:19:55Z")

</div>

All,

I am trying to execute the following SQL code and have the result  
returned to my application for further proessing…

“select SUM(action) as ‘sum’ from approvals where upload\_id = ?”,  
@upload.id

I have tried this in a Approval.find\_by\_sql also as a  
Approval.connection.execute, but I can’t seem to get the data back  
into rails… How can I access the returned data, which should be a  
single number? I tried @points.sum, @points, etc. I want to do some  
numerical comparisons on this, so I need the number, and just the  
number.

Oh, and `action` can be any number from -3 to 3, so I can’t just do a  
count…

Any ideas?

Thanks!

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [April 20, 2007, 11:04am UTC](https://www.ruby-forum.com/t/doing-a-sql-sum-and-getting-the-result-into-rails/92522/2 "2007-04-20T11:04:22Z")

</div>

Approval.sum ‘action’, :conditions =\> [‘upload\_id = ?’, @upload.id]  
should do the trick.

If you go down the road of writing out the sql by hand (not necessary  
here, but things aren’t always as simple) then you can use  
Approval.connection.select\_values

Fred
