[英]How to order grouped columns in an ActiveRecord Postgres query
我正在嘗試為包含相當標准的存檔信息的博客構建側邊欄,例如:
2013年8月:3個帖子
2013年7月:5個帖子
2013年6月:4個帖子
...等等
哪個ActiveRecord查詢將提供按時間順序反向排序的該信息( month
, year
, count
)?
post模型很簡單- title
, body
, created_at
, modified_at
列。 我正在嘗試編寫ActiveRecord / Postgres查詢,該查詢為我提供了按月和年分組的帖子數(如上所列)。 以下查詢成功地做到了這一點:
Post.select('count(*) as count','extract(year from created_at) as year', 'extract(month from created_at) as month').group('year','month')
但是我想按時間順序顯式地對列進行排序(因此,清單中的2013年8月高於2013年7月),這就是一切的麻煩。 我嘗試嘗試以下查詢失敗,只是為了開始:
Post.select('count(*) as count','extract(year from created_at) as year', 'extract(month from created_at) as month').group('year','month').order(:year => :desc)
它產生以下SQL:
SELECT count(*) as count, extract(year from created_at) as year, extract(month from created_at) as month FROM "posts" GROUP BY year, month ORDER BY "posts"."year" DESC
並出現以下錯誤:
PG::UndefinedColumn: ERROR: column posts.year does not exist
如果我使用.order(:count => :desc)
進行計數排序,則查詢實際上會運行,但實際上似乎並沒有按照我期望的方式進行排序(切換到:asc
並沒有什么不同)。
我已經搜索過SO和Google,但都無濟於事。 我也嘗試過按created_at
排序,但是會引發ActiveRecord::StatementInvalid: PG::GroupingError: ERROR: column "posts.created_at" must appear in the GROUP BY clause or be used in an aggregate function
錯誤中使用。 理想情況下,我將運行一個簡單的Post.order(:created_at => :desc)
,然后對排序良好的結果運行分組查詢,但我不知道如何進行。
非常迷茫...我如何檢索帶有year
和month
的帖子並count
列,但如何按時間順序對結果組進行排序?
在此先感謝您的幫助!
並非所有數據庫都允許您在GROUP
或ORDER
子句中引用派生的列名。 我自己不了解PostgreSQL,但也許它支持相對的列引用。 嘗試這個:
SELECT count(*) as count
, extract(year from created_at) as year
, extract(month from created_at) as month
FROM "posts"
GROUP BY 2, 3
ORDER BY 2 DESC, 3 DESC
如果這不起作用,則應該:
SELECT count(*) as count
, extract(year from created_at) as year
, extract(month from created_at) as month
FROM "posts"
GROUP BY extract(year from created_at), extract(month from created_at)
ORDER BY extract(year from created_at) DESC, extract(month from created_at) DESC
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.