2017-05-08 62 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.

這裏的問題是,在PostgreSQL裏你必須要明確哪些發票要顯示的due_date,而在MySQL或SQLite的會選擇一個(可以」不要忘記我的頭頂是如何的)。在這種情況下,我認爲從select中省略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") 

這將總結平衡和選擇「隨機」 DUE_DATE/total_mount每個CUSTOMER_ID。就像那兩個其他RDBMS中的非標準GROUP BY一樣。

+0

謝謝。我想嘗試。 – akbarbin

相關問題