sql - Generating a subquery with Arel to get an average of averages -


lets have few of tables

orders = arel::table.new :orders stores = arel::table.new :stores managers = arel::table.new :managers 

and manager has many stores , store has many orders.

one day want query average total across orders manager works. oh, want group store. clear, want average order total manager, each of stores work at.

and let's assume we've looked 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`) avg_id `orders` `orders`.`store_id` in (1, 2, 3) group `orders`.`store_id`" 

yup, works great. how can query average of averages?

what's arel query?

"select avg(avg_id) (select avg(`orders`.`total`) avg_id `orders` `orders`.`store_id` in (1, 2, 3) group `orders`.`store_id`) avg_id_alias;" 

anybody know?

you can pretty close, activerecord doesn't support execution of arel structures directly, have convert them sql first.

here's example of similar you're doing:

o = orders.arel_table o_avg = orders.select(:avg[:store_id].as('avg_id')).               where(:store_id => [1,2,3]).group(:store_id)  orders.find_by_sql("select avg(avg_id) (#{o_avg.to_sql})") 

be happy compromise. activerecord poorly suited gather aggregate data about more 1 model @ time, , if wisely leery of patching sql together, arel can server adequate tool it.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

android - layout with fragment and framelayout replaced by another fragment and framelayout -