2014-12-31 27 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")