1

Anyone know how I can create this query using ActiveRecord rather than using SQL?

@leaderboard = ActiveRecord::Base.connection.execute("SELECT name, street, town, county,        avg(volume_used)  FROM `DBName`.`events
join DBName.households on idhouseholds = events.household_id 
group by household_id
order by volume_used ASC;");
1
  • Your ActiveRecord connection will be to a specific database. You'll need to connect to DBName (by specifying the correct params in database.yml) before running your query. Commented Jul 13, 2011 at 12:13

1 Answer 1

1

How about...

@leaderboard = Event.select([:name,:street,:town,:county,'avg(volume_used) as avg_used']).joins(:households).group('events.household_id').order('volume_used asc')

assuming that by idhouseholds you actually meant households.id and that you want to order by the aggregate average field you are selecting.

Sign up to request clarification or add additional context in comments.

5 Comments

thanks Ben, tried that and its giving me incorrect averages and its dropping records too. Any other suggestions?
Can you post your table definitions?
create_table :events do |t| t.integer :id t.datetime :start_time t.datetime :end_time t.float :volume_used t.integer :inferred_appliance_id t.integer :household_id t.timestamps end
create_table :households do |t| t.string :name t.string :number t.string :street t.string :town t.string :county end
Thanks. I've updated the code in the answer (the order and group clauses weren't quite right) - give that a try.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.