[英]How to group by day and year in Active Record in Rails3
我正在尝试在rails 3中重新创建以下mysql查询
select count(id), year(created_at), month(created_at) from table where published_state = 'published' group by year(created_at), month(created_at);
我尝试过类似的东西:
results = Table.select('count(id), year(created_at), month(created_at)').where('published_state LIKE ?', 'published').group('year(created_at), month(created_at)')
但它不会返回我想要的东西。
我只是得到了回报
[#<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >,
#<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >, #<Table >]
我怎么能做到这一点?
谢谢!
试试这个:
Table.where(:published_state => 'published').
group('year(created_at)').group('month(created_at)').count(:id)
结果的格式并不是我所期望的(它是一个像[year, month]
和计数值这样的数组键的哈希),但它可能会满足你的目的吗?
如果您正在使用PostgreSQL,您还可以使用date_trunc函数(为了便于阅读而分割行,但可能无法在真正的Ruby中使用):
Table.select('count(id), date_trunc('month', created_at) as month')
.where('published_state LIKE ?', 'published').group('month')
基本上,它会截断或切断不再重要的日期部分。 例如,如果您选择“月”,它仍会保留带月份的年份,但不保留日期和时间。
我可能也会这样订购:
Table.select('count(id), date_trunc('month', created_at) as month')
.where('published_state LIKE ?', 'published').group('month')
.order('month' DESC)
.limit(24)
在这里阅读更多文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.