Rails计算字段的活动记录计数

时间:2013-02-15 22:33:35

标签: ruby-on-rails rails-activerecord arel

使用AREL / Rails calculations我正在尝试执行以下操作:

SELECT to_char(timestamp, 'YYYY-MM-DD') AS segment, COUNT(*) AS counter 
FROM pages
GROUP BY segment
ORDER BY segment

我可以运行类似的东西:

Page.order(FIELD).count(group: FIELD) 
{ a: 1, b: 4, c: 1 }

但是,我不能在计算字段中使用它。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

想出了这个:

Page.count(:all, from: "(SELECT to_char(#{SEGMENT}, 'YYYY-MM-DD')  AS segment FROM pages) AS pages", group: "segment", order: "segment")
> SELECT COUNT(*) AS count_all, segment AS segment FROM (SELECT to_char(created_at, 'YYYY-MM-DD') AS segment FROM pages) AS pages GROUP BY segment ORDER BY segment