# Averaging data with Activerecord

**URL:** <https://www.ruby-forum.com/t/averaging-data-with-activerecord/111202>\
**Category:** Rails\
**Created:** [August 3, 2007, 7:53pm UTC](https://www.ruby-forum.com/t/averaging-data-with-activerecord/111202 "2007-08-03T19:53:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![chirag](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/ecccb3/32.png) [@chirag](https://www.ruby-forum.com/u/chirag)\
**Post date:** [August 3, 2007, 7:53pm UTC](https://www.ruby-forum.com/t/averaging-data-with-activerecord/111202/1 "2007-08-03T19:53:42Z")

</div>

I have a database table of timestamped scalars with each row (scalar)  
added every 15 seconds. I want to process a day’s worth of data so  
that an average scalar of every 30 minutes is returned. I would like  
to return the averaged data in an array. What is the most effecient  
way to do this with performance in mind? Could the ‘group’ option in  
the ‘average’ method for a model be used?

Thanks,  
Chirag

---

<div class="post-metadata">

**Author:** ![chirag](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/ecccb3/32.png) [@chirag](https://www.ruby-forum.com/u/chirag)\
**Post date:** [August 3, 2007, 9:00pm UTC](https://www.ruby-forum.com/t/averaging-data-with-activerecord/111202/2 "2007-08-03T21:00:53Z")

</div>

What’s a scalar in this context ? Did I miss something ?

If you’re looking for raw performance, write a stored procedure.

On 8/3/07, chirag [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> >

–  
Cheers!

- Pratik  
[http://m.onkey.org](http://m.onkey.org)

---

<div class="post-metadata">

**Author:** ![chirag](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/ecccb3/32.png) [@chirag](https://www.ruby-forum.com/u/chirag)\
**Post date:** [August 3, 2007, 9:20pm UTC](https://www.ruby-forum.com/t/averaging-data-with-activerecord/111202/3 "2007-08-03T21:20:55Z")

</div>

> I have a database table of timestamped scalars with each row  
> (scalar) added every 15 seconds. I want to process a day’s  
> worth of data so that an average scalar of every 30 minutes  
> is returned. I would like to return the averaged data in an  
> array. What is the most effecient way to do this with  
> performance in mind? Could the ‘group’ option in the  
> ‘average’ method for a model be used?

ActiveRecord doesn’t really have much to offer you in this regard, this  
is largely a pure SQL question. What you need to do is add a column to  
the resultset with the time rounded to the nearest half an hour - either  
by decorating the data with a view or, probably more efficiently, doing  
it on insert. Given that, you can easily average and group the data  
either in raw SQL or using ActiveRecord’s aggregation methods. The  
latter might look like:

Timestamps.average(:scalar, :group=\>‘half\_hour’)

- donald
