2013-04-24 202 views
0

的表是:獲得總筆數的總和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

「*不工作將它們添加到選擇線和組* 「不是有效的Postgres錯誤消息。 – 2013-04-24 09:13:32

+0

PG ::錯誤:錯誤:當前事務中止,命令被忽略,直到事務塊結束< - 錯誤 – 2013-04-24 09:14:25

+0

這不是與您的查詢相關的錯誤消息。這是以前錯誤的結果。 – 2013-04-24 09:16:53

回答

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 

如果你想在輸出更多的列,一行