问题
This is my query.
ShopifyOrderLineItem.select("shopify_order_line_items.*, sum(amount) as total_price, sum(quantity) as total_quantity").where(:vendor_id => vendor_id).group("shopify_order_line_items.title")
I'm getting the following exception.
PG::GroupingError: ERROR: column "shopify_order_line_items.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT shopify_order_line_items.*, sum(amount) as total_pric...
Any suggestions?
I have tried this but it doesn't work.
ShopifyOrderLineItem.select("shopify_order_line_items.*, count(shopify_order_line_items.id) as unique_ids, sum(amount) as total_price, sum(quantity) as total_quantity").where(:vendor_id => vendor_id).group("shopify_order_line_items.title")
回答1:
When you want to do a aggregation like SUM or COUNT, you can only select the columns on which you do the GROUP BY.
ShopifyOrderLineItem.select("shopify_order_line_items.title, count(shopify_order_line_items.id) as unique_ids, sum(amount) as total_price, sum(quantity) as total_quantity").where(:vendor_id => vendor_id).group("shopify_order_line_items.title")
来源:https://stackoverflow.com/questions/23433016/ruby-on-rails-must-appear-in-the-group-by-clause-or-be-used-in-an-aggregate-fun