2014-04-02 62 views
1
Score.where(period: ["q1", "q2"]).pluck(:game_id, :home_score, :away_score) 

該查詢返回的結果是這樣的:Rails的查詢 - 和結果

[[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]] 
+0

你有模型叫做遊戲嗎? – BroiSatse

+0

是的,我確實有一個模型叫做遊戲 – appleLover

回答

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]} 
+1

我會接受這個答案,因爲查詢不需要遊戲表,並且對我來說更直觀。不知道這是否是不好的標準。公認。 – appleLover

3

假設game_id是映射到遊戲對象的外鍵,請嘗試:

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] 

無法對其進行測試,但它應該與單個數據庫查詢一起使用。