2017-05-08 65 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

相关问题