I'm trying to convert ruby query to sql here is what I got so far:
sql2 = "SELECT teams.* FROM teams, (SELECT sum(goals) FROM players WHERE team_id = team_id);"
connection.execute(sql2)
and this is what I'm trying to write:
Team Load (0.6ms) SELECT "teams".* FROM "teams"
(0.5ms) SELECT SUM("players"."goals") FROM "players" WHERE "players"."team_id" = $1 [["team_id", 1]]
(0.5ms) SELECT SUM("players"."goals") FROM "players" WHERE "players"."team_id" = $1 [["team_id", 2]]
the above was created with : Team.all.map {|t| puts "#{t.name} and #{t.players.sum(:goals)}"}
a simple loop trough players, getting team name and summing team.players.goals
Ideas would be appreciated
SELECT sum(goals) FROM players GROUP BY team_idwould do the trick. Or, if you want exactly what stupid AR does:SELECT sum(goals) FROM players WHERE team_id IN (SELECT id FROM teams).