# Arel average of averages

**URL:** <https://www.ruby-forum.com/t/arel-average-of-averages/203948>\
**Category:** Rails\
**Created:** [March 2, 2011, 9:15am UTC](https://www.ruby-forum.com/t/arel-average-of-averages/203948 "2011-03-02T09:15:33Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dubstep](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/cdc98d/32.png) [@dubstep](https://www.ruby-forum.com/u/dubstep)\
**Post date:** [March 2, 2011, 9:15am UTC](https://www.ruby-forum.com/t/arel-average-of-averages/203948/1 "2011-03-02T09:15:33Z")

</div>

Lets say I have a few of tables

orders = Arel::Table.new :orders  
stores = Arel::Table.new :stores  
managers = Arel::Table.new :managers

And a manager has many stores and a store has many orders.

One day I want to query for the average total across orders where a  
manager works. Oh, I want to group that by the store. So to be clear,  
I want to get the average order total for a manager, for each of the  
stores they work at.

And let’s assume we’ve looked up our manager:

```
manager = Manager.find(some_id)

```

totals =  
orders.where(orders[:store\_id].in(manager.store\_ids)).group(orders.store\_id).project(orders[:total].average)

puts totals.to\_sql

“SELECT AVG(`orders`.`total`) AS avg\_id FROM `orders` WHERE  
`orders`.`store_id` IN (1, 2, 3) GROUP BY `orders`.`store_id`”

Yup, that works great. But how can I get a query for the average of  
those averages?

What’s the Arel to get this query?

“SELECT AVG(avg\_id) FROM (SELECT AVG(`orders`.`total`) AS avg\_id FROM  
`orders` WHERE `orders`.`store_id` IN (1, 2, 3) GROUP BY  
`orders`.`store_id`) as avg\_id\_alias;”

Anybody know?
