2017-05-08 8 views
-2

PostGreSQLで問題が発生しました。PosGreSQL ActiveRecord :: StatementInvalid:PG :: GroupingError:エラー:GROUP BYに表示する必要があります。

Invoice.select("customer_id, due_date, sum(balance) AS total_balance, total_mount").group(:customer_id) 

以下の私のコードは、私はエラー

Invoice Load (1.8ms) SELECT customer_id, due_date, sum(balance) AS total_balance, total_amount FROM "records" WHERE "records"."type" IN ('Invoice') GROUP BY "records"."customer_id" 
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "records.due_date" must appear in the GROUP BY clause or be used in an aggregate function 
enter code here 
LINE 1: SELECT customer_id, due_date, sum(balance) AS total_balance,... 

UPDATEソリューションの@slicedpanため

感謝を持っています。私は以下のコードのような更新があります。

Invoice.select("customer_id, MAX(due_date), SUM(balance) AS total_balance").group(:customer_id) 

私はそれについて多くの記事を読んだことがありますが、まだエラーが表示されます。ありがとう

答えて

1

このエラーは、Postgresがdue_dateカラムの処理方法を知らないためです。あなたが書かれているクエリは、基本的には、次のとおりです。

for each customer, show me the total sum of the balances for all their invoices, and the due date for one of their invoices.

ここでの問題は、MySQLやSQLiteの中で、それは(「できるものを選ぶだろう、一方、PostgreSQLではあなたは、あなたがのdue_dateを表示したい請求書かについて明示しなければならないことですどのように私の頭の上を覚えていない)。このケースでは、選択からDue_dateを除外する方が理にかなっていると思います。そうでない場合は、MAX(due_date)を使用して最新のものを取得してください。あなたはこのようにそれを行う場合

+0

ありがとうございます。私は最初に試してみたい。 – akbarbin

+0

ありがとうございました。それは今働いている。 – akbarbin

1

あなたは、MySQL/SQLiteのと同じ機能を得ることができます。

Invoice.select("DISTINCT ON (customer_id) customer_id, due_date, sum(balance) over(partition by customer_id) AS total_balance, total_mount") 

それはバランスを合計し、各CUSTOMER_IDのために「ランダム」DUE_DATE/total_mountを選択します。他の2つのRDBMSでは非標準のGROUP BYと同じようにできます。

+0

ありがとうございます。やってみたい。 – akbarbin

関連する問題