0

我有以下 postgresql 语句,它在 Navicat for Postgresql 中工作正常,

SELECT date_trunc('day', updated_at), count(*) as total_count 
FROM "persons"
WHERE ("persons"."updated_at" BETWEEN '2012-10-17 00:00:00.000000' AND '2012-11-07   12:25:04.082224') 
GROUP BY date_trunc('day',updated_at)
ORDER BY count(updated_at) DESC

我得到了预期的结果

2012-10-31 00:00:00,5
2012-11-06 00:00:00,2
2012-11-05 00:00:00,1

我需要将其转换为 ruby​​ 用于 RoR 项目

我写了这个声明如下

persons = where(updated_at: start.beginning_of_day..Time.zone.now)
persons = persons.group("date(updated_at)")
persons = persons.select("updated_at, count(*) as total_count")
persons = persons.order("count(updated_at)")

但是我收到以下错误

PG::Error: ERROR:  column "persons.updated_at" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT updated_at, count(*) as total_count FROM "persons"  WH...
           ^
: SELECT updated_at, count(*) as total_count FROM "persons"  WHERE ("persons"."updated_at"     BETWEEN '2012-10-17 00:00:00.000000' AND '2012-11-07 14:38:54.674684') GROUP BY     date(persons.updated_at) ORDER BY count(updated_at)

关于我做错了什么的任何想法?

4

2 回答 2

1

您正在选择updated_at,但您正在分组date(updated_at)。您要么需要分组updated_at(这可能没有任何意义),要么更改您的选择,以便您选择date(updated_at).

换句话说,以 Jon Day 的第二个例子为例。

于 2012-11-07T16:56:13.927 回答
1

也许你可以试试

persons = where(updated_at: start.beginning_of_day..Time.zone.now)
persons = persons.group("date(updated_at), updated_at")
persons = persons.select("updated_at, count(*) as total_count")
persons = persons.order("count(updated_at)")

或者

persons = where(updated_at: start.beginning_of_day..Time.zone.now)
persons = persons.group("date(updated_at)")
persons = persons.select("date(updated_at), count(*) as total_count")
persons = persons.order("count(updated_at)")

或者

persons = persons.find(:all, 
                       :select => "updated_at, count(*) as total_count",
                       :group => "updated_at",
                       :order => "count(updated_at)")  
于 2012-11-07T15:04:30.773 回答