2012-11-07 94 views
0

我有以下的PostgreSQL的聲明,在Navicat PostgreSQL的工程確定,紅寶石Postgresl組聲明

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 

我需要將它轉換爲紅寶石的回報率項目

我寫了這樣的聲明如下

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) 

什麼,我做錯了什麼想法?

回答

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)") 
+0

我用中間選項指定了一些成功,但現在我得到了另一個錯誤。 ActiveModel :: MissingAttributeError:缺少屬性:狀態。狀態是我的Person類中的一個屬性。 –

+0

我也嘗試完善查詢,通過=其中(updated_at:start.beginning_of_day..Time.zone.now) passes = passes.group(「date(updated_at)」) passes = passes.select( 「date(updated_at),count(*)as total_count」)。但現在我得到(對象不支持#inspect) –

+0

對不起,應該是人不通過 –

1

您選擇updated_at,但你上進行分組date(updated_at)。您或者需要對updated_at進行分組(可能沒有任何意義),或者更改您的選擇,以便您選擇date(updated_at)

換句話說,以Jon Day的第二個例子。