Rails:必须出现在GROUP BY子句中或用于聚合函数

时间:2013-07-26 22:48:14

标签: ruby-on-rails postgresql

我正在跟随Bate对图表的关注&图表,但我得到一个错误。

这是我得到的错误

PG::Error: ERROR:  column "orders.created_at" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT created_at, sum(amount) as total_amount FROM "orders"...
               ^
: SELECT created_at, sum(amount) as total_amount FROM "orders"  WHERE ("orders"."created_at" BETW

这是我在订单模型中使用的代码

def self.total_grouped_by_day(start)
    orders = where(created_at: start.beginning_of_day..Time.zone.now)#.all
    orders = orders.group("date(created_at)")
    orders = orders.select("date(created_at), sum(amount) as total_amount")
    orders.group_by { |order| order.created_at.to_date }
  end

和我的助手

def orders_chart_data
        orders_by_day = Order.total_grouped_by_day(3.weeks.ago)
        (3.weeks.ago.to_date..Date.today).map do |date|
            {
                created_at: date,
                price: orders_by_day[date].first.try(:total_amount) || 0
            }
        end
    end

我正在使用Postgres(我很确定这是我收到此错误的主要原因)& Rails 3.x.x. 为什么会发生此错误&我该如何解决?

提前谢谢


在我的控制台中:

Order.where(created_at: 3.weeks.ago.beginning_of_day..Time.zone.now).group("date(created_at)").select("date(created_at), sum(amount) as total_amount")

&安培;这就是我得到的

[#<Order >, #<Order >, #<Order >] 

怪异..


在我的控制台中运行:Order.where(created_at: 3.weeks.ago.beginning_of_day..Time.zone.now).group("date(created_at)").select("date(created_at), sum(amount) as total_amount").first.total_amount

给了我这个:

Creating scope :page. Overwriting existing method Order.page.
  Order Load (18.1ms)  SELECT date(created_at), sum(amount) as total_amount FROM "orders" WHERE ("orders"."created_at" BETWEEN '2013-07-05 00:00:00.000000' AND '2013-07-26 23:50:38.876609') GROUP BY date(created_at) LIMIT 1
 => "10.0"

2 个答案:

答案 0 :(得分:6)

您正在date(created_at)进行分组,但未选择该列。改变这一行:

orders = orders.select("created_at, sum(amount) as total_amount")

到此:

orders = orders.select("date(created_at), sum(amount) as total_amount")

这也会导致下一行的group_by发生变化。

从我的一个项目中,使用稍微不同的属性,但做同样的事情:

1.9.3p327 > User.group('date(created_at)').select('date(created_at), sum(id) as total_amount').first.attributes
  User Load (1.2ms)  SELECT date(created_at), sum(id) as total_amount FROM "users" GROUP BY date(created_at) LIMIT 1
 => {"date"=>"2011-09-27", "total_amount"=>"657"}

答案 1 :(得分:1)

迄今为止演员阵容最简单&amp;最快的。这里是原始的SQL,因为我不是Ruby语法的专家(并且没有一般的ORMs屠杀SQL的粉丝)。

SELECT created_at::date, sum(amount) AS total_amount
FROM   orders
WHERE  created_at ...
GROUP  BY created_at::date
ORDER  BY created_at::date