【问题标题】:PostgreSQL ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: must appear in the GROUP BYPostgreSQL ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: 必须出现在 GROUP BY
【发布时间】:2017-05-08 09:24:49
【问题描述】:

我在 PostGreSQL 中有困难组。下面是我的代码

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,...

更新

感谢@slicedpan 的解决方案。我有更新如下代码。

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

我已经阅读了很多关于此的文章,但它仍然显示错误。

【问题讨论】:

    标签: ruby-on-rails postgresql activerecord


    【解决方案1】:

    这个错误是由于 Postgres 不知道如何处理 due_date 列。你写的查询基本上是:

    对于每个客户,向我显示他们所有发票的余额总和,以及其中一张发票的到期日期。

    这里的问题是,在 PostgreSQL 中,您必须明确说明要显示哪张发票的 due_date,而在 MySQL 或 SQLite 中,它会选择一张(不记得我是怎么想的) .在这种情况下,我认为从选择中省略due_date 会更有意义,否则使用MAX(due_date) 获取最新的,或类似的东西。

    【讨论】:

    • 谢谢。我想先试试。
    【解决方案2】:

    如果你这样做,你可以获得与 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 选择“随机”到期日期/总金额。就像其他 2 个 RDBMS 中可能的非标准 GROUP BY 一样。

    【讨论】:

      猜你喜欢
      • 2015-04-20
      • 2017-02-28
      • 1970-01-01
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-03
      • 1970-01-01
      相关资源
      最近更新 更多