# Counting / Aggregation Queries

**URL:** <https://www.ruby-forum.com/t/counting-aggregation-queries/151457>\
**Category:** Rails\
**Created:** [October 21, 2008, 9:08pm UTC](https://www.ruby-forum.com/t/counting-aggregation-queries/151457 "2008-10-21T21:08:44Z")\
**Posts on this page:** 2\
**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:** [October 21, 2008, 9:08pm UTC](https://www.ruby-forum.com/t/counting-aggregation-queries/151457/1 "2008-10-21T21:08:44Z")

</div>

Hi all,

Suppose you have two models – one for Files and anther for Downloads  
– such that a file has\_many =\> :downloads

If you wanted to get a count of the downloads for the current month  
and the two previous months, is there a way to get that data from one  
query? Something like:

@file.downloads\_for\_month( 2008, 10 )

where 2008 is the year and 10 is the month…

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:** [October 21, 2008, 9:54pm UTC](https://www.ruby-forum.com/t/counting-aggregation-queries/151457/2 "2008-10-21T21:54:02Z")

</div>

named\_scope is your friend

class Download \< ActiveRecord::Base  
belongs\_to :file

named\_scope :between, lambda{ |start\_date, end\_date| { :conditions  
=\> [“created\_at \>= ? AND created\_at \< ?”, start\_date, end\_date] } }  
named\_scope :from\_file, lambda { |file| { :conditions =\> [“file\_id  
= ?”, file.id] } }  
end

Download.between(“2008-10-01”.to\_date,  
“2008-11-01”.to\_date).from\_file(file).count
