Rails查询 - 求和结果

时间:2014-04-02 00:06:05

标签: ruby-on-rails ruby sum

Score.where(period: ["q1", "q2"]).pluck(:game_id, :home_score, :away_score)

此查询返回如下结果:

[[57927, 26, 19], [57927, 28, 23], 
[57928, 12, 21], [57928, 17, 25], 
[57929, 28, 15], [57929, 24, 20]]

我如何总结:home_score和:away_score相同的结果:game_id,以获得此

[[57927, 54, 42], 
[57928, 29, 46], 
[57929, 52, 35]]

2 个答案:

答案 0 :(得分:3)

假设game_id是映射到Game对象的外键,请尝试:

Game.joins(:scores).select("#{Game.table_name}.id, SUM(#{Game.table_name}.home_score) AS home_total, SUM(#{Game.table_name}.away_score) AS total_away").group("#{Game.table_name}.id").pluck[:id, :home_total, :away_total]

无法对其进行测试,但它应该适用于单个数据库查询。

答案 1 :(得分:1)

您需要使用group子句。

Score.where(period: ["q1", "q2"]).group(:game_id)
    .select('game_id, sum(home_score) as home_score_sum, sum(away_score) as away_score_sum')
    .all.map {|s| [s.game_id, s.home_score_sum, s.away_score_sum]}