获得PostgreSQL中Total项的总和

时间:2013-04-24 09:09:57

标签: ruby-on-rails postgresql

表格是:

Orders
-----------
user_id
state


Items
-----------
order_id
product_id
total

Products
----------
user_id


Users
---------
name
email

关系如下:

User
has_many :products

Order
has_many :items
belongs_to :users

Product
has_many :items
belongs_to :user

Item
belongs_to :items

我想获得拥有该产品的每个用户的items.total总和

我目前有以下SQL语句:

SELECT *, SUM(items.total) as totalprice 
FROM "orders" 
INNER JOIN "items" ON "items"."order_id" = "orders"."id"
INNER JOIN "products" ON "products"."id" = "items"."product_id"
INNER JOIN "users" ON "users"."id" = "products"."user_id"
WHERE "orders"."state" = 'complete'
GROUP BY users.id

OR

Order.complete.joins(:items => {:product => :user}).select("*, SUM(items.total) as totalprice").group('users.id')

以上不起作用。我觉得这应该很容易。

1 个答案:

答案 0 :(得分:2)

在分组查询中,您需要包括group by子句中未聚合的所有列。如果您将查询更改为此,您可能会有更好的运气

SELECT users.id, SUM(items.total) as totalprice 
FROM "orders" 
INNER JOIN "items" ON "items"."order_id" = "orders"."id"
INNER JOIN "products" ON "products"."id" = "items"."product_id"
INNER JOIN "users" ON "users"."id" = "products"."user_id"
WHERE "orders"."state" = 'complete'
GROUP BY users.id

如果您想在输出中添加更多列,请将它们添加到选择行和逐行分组