# More concise way to write aggregate query

**URL:** <https://www.ruby-forum.com/t/more-concise-way-to-write-aggregate-query/163856>\
**Category:** Rails\
**Created:** [March 25, 2009, 3:47pm UTC](https://www.ruby-forum.com/t/more-concise-way-to-write-aggregate-query/163856 "2009-03-25T15:47:23Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Neal\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/74df32/32.png) [@Neal\_L](https://www.ruby-forum.com/u/Neal_L)\
**Post date:** [March 25, 2009, 3:47pm UTC](https://www.ruby-forum.com/t/more-concise-way-to-write-aggregate-query/163856/1 "2009-03-25T15:47:23Z")

</div>

Hi all,

Just curious if anyone knows a cleaner way to write this query…

def payments\_for(start\_on, end\_on)  
sum = 0  
self.leases.each { |lse|  
sum += lse.payments.within(start\_on, end\_on).sum(:amount)  
}  
sum  
end

Thanks!

---

<div class="post-metadata">

**Author:** ![Neal\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/74df32/32.png) [@Neal\_L](https://www.ruby-forum.com/u/Neal_L)\
**Post date:** [March 25, 2009, 4:35pm UTC](https://www.ruby-forum.com/t/more-concise-way-to-write-aggregate-query/163856/2 "2009-03-25T16:35:32Z")

</div>

On Mar 25, 2009, at 10:46 AM, Neal L wrote:

> sum  
> end
> 
> Thanks!

NOTE: This is completely off the top of my head and quite possibly  
contains bugs 😉

has\_many :leases do  
def payments\_for(start\_on, end\_on)  
select\_value(“SELECT SUM(payments.amount) FROM payments INNER  
JOIN leases ON leases.id = payments.lease\_id WHERE  
#{proxy\_owner.class.send(:sanitize\_sql, [‘payments.paid\_on BETWEEN ?  
AND ? AND leases.some\_parent\_id = ?’, start\_on, end\_on,  
proxy\_owner.id])}”)  
end  
end

Actually, I realize that I’m thinking of ‘more performant’ rather than  
‘cleaner’ by shifting some work to the database. Since I don’t know  
where the #within method comes from (named\_scope perhaps?), I really  
can’t say too much. Your solution is actually quite clean. What  
prompted you to ask the question?

-Rob

Rob B. [http://agileconsultingllc.com](http://agileconsultingllc.com)  
removed\_email\_address@domain.invalid

---

<div class="post-metadata">

**Author:** ![Neal\_L](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/n/74df32/32.png) [@Neal\_L](https://www.ruby-forum.com/u/Neal_L)\
**Post date:** [March 25, 2009, 8:04pm UTC](https://www.ruby-forum.com/t/more-concise-way-to-write-aggregate-query/163856/3 "2009-03-25T20:04:12Z")

</div>

I was reading about symbol to proc and thought there might be a use  
here… Yes, within() is a named\_scope.

Thanks!

On Mar 25, 10:35 am, Rob B. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
