2014-12-31 30 views
1

這裏相當於是我的問題,我發展與Ruby on Rails的web應用程序和我卡在一個特定的查詢總和特定值的特定鍵時,在紅寶石

我有表purchase_item其中包含: user_iditem_idamounttotal, ...

我想量和總的總和時user_iditem_id是相同的。

所以在這裏:

@purchase_items = PurchaseItem.all 
@purchase_items = ? 
+0

你試過任何疑問? –

+0

我嘗試了一些選擇,合併...但每次我得到錯誤 – Thounder

+2

然後發佈您的查詢 –

回答

0

試試下面的查詢:

PurchaseItem.select("SUM(purchase_items.amount) AS total_amount, SUM(purchase_items.total) AS total_value").where("user_id = ? AND item_id =?", user_id, item_id).group(:user_id) 

這可能會爲你工作。

+0

這看起來像我試過,但我不能使用where子句,因爲user_id和item_id是在表purchase_item內。 只有當purchase_item 1具有與purchase_item 2相同的user_id和item_id時,行才需要求和。... – Thounder

+0

爲此,您可以按兩列「PurchaseItem.group([:user_id,:item_id])」進行分組。select 「SUM(purchase_items.amount)AS total_amount,SUM(purchase_items.total)AS total_value」)'或'PurchaseItem.group([:user_id,:item_id])。sum(:amount,:total)' –

+0

仍然無法運行嘗試另一種方式。現在我已經: [{「item」=> 31,「amount」=> 1,「total」=>#,「user」=> 25}, {「item」=> 31,「amount」=> 1,「total」=>#,「user」=> 25}] 我需要: [{「item」=> 31,「amount」=> amount1 + amount2,「total」=> total1 + total2,「user」=> 25}] – Thounder

0

嘗試這樣的: -

amount = PurchaseItem.where("user_id = ? and item_id = ?", user_id,item_id).sum("amount") 
total = PurchaseItem.where("user_id = ? and item_id = ?", user_id,item_id).sum("total")