我正在关注一个railscast剧集,但我正在使用postgresql并且收到了group_by错误:
PG::Error: ERROR: column "ratings.created_at" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT created_at, sum(score) as total_score FROM "ratings" ...
^
: SELECT created_at, sum(score) as total_score FROM "ratings" WHERE ("ratings"."created_at" BETWEEN '2014-01-02 00:00:00.000000' AND '2014-01-23 13:43:06.187741') GROUP BY date(created_at)
我应该如何修改下面的代码以包含group_by created_at
def self.chart_data(start = 3.weeks.ago)
total_votes = votes_by_day(start)
(start.to_date..Date.today).map do |date|
{
created_at: date,
total_score: total_prices[date] || 0
}
end
end
def self.votes_by_day(start)
ratings = where(created_at: start.beginning_of_day..Time.zone.now)
ratings = ratings.group("date(created_at)")
ratings = ratings.select("created_at, sum(score) as total_score")
ratings.each_with_object({}) do |rating, scores|
scores[rating.created_at.to_date] = rating.total_score
end
end
答案 0 :(得分:2)
您的group by子句和您的select子句具有不同的属性。如果您按" date(created_at)"进行分组然后你就不能再选择" created_at。"
def self.votes_by_day(start)
ratings = where(created_at: start.beginning_of_day..Time.zone.now)
ratings = ratings.group("date(created_at)")
ratings = ratings.select("date(created_at), sum(score) as total_score")
ratings.each_with_object({}) do |rating, scores|
scores[rating.created_at.to_date] = rating.total_score
end