# Group\_by

**URL:** <https://www.ruby-forum.com/t/group-by/180027>\
**Category:** Rails\
**Created:** [December 9, 2009, 11:41pm UTC](https://www.ruby-forum.com/t/group-by/180027 "2009-12-09T23:41:18Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![rjsquire](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/74df32/32.png) [@rjsquire](https://www.ruby-forum.com/u/rjsquire)\
**Post date:** [December 9, 2009, 11:41pm UTC](https://www.ruby-forum.com/t/group-by/180027/1 "2009-12-09T23:41:18Z")

</div>

Hi! I’m hoping somebody may be able to help with my group\_by problems  
using some information that I imported from Google Analytics.

I’ve been trying to accomplish two things:

1. Inside the Stat table, I’ve been trying to sum up all pageviews for a  
given month, where the date of the record is stored as YYYY-MM-DD in the  
field named “date”. The current group\_by works fine for pulling out the  
individual records by month, but I can’t figure out how to use sum to do  
the same for pageviews over the whole month.

2. This is probably significantly more difficult, but can you do a  
group\_by over multiple fields? Specifically, I wanted to group by  
site\_id and then by month.

I hope these requests aren’t too much, but any assistance is  
appreciated.

def index  
@gatotals = Stat.find(:all)  
@ga\_months = @gatotals.group\_by { |t| t.date.month }  
end

index.html.erb

\<% @ga\_months.sort.each do |month, records| %\>  
\<%= monthname(month) %\>  
\<% for record in records %\>  
\<%= record.date %\>  
\<%= number\_with\_delimiter(record.pageviews, :separator =\> “,”) %\>  
\<% end %\>  
\<% end %\>
