Mysql 如何在Rails3的活动记录中按日期和年份分组
我正在尝试在rails 3中重新创建以下mysql查询Mysql 如何在Rails3的活动记录中按日期和年份分组,mysql,ruby-on-rails,ruby-on-rails-3,activerecord,group-by,Mysql,Ruby On Rails,Ruby On Rails 3,Activerecord,Group By,我正在尝试在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(crea
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]
和count value),但它可能会满足您的需要?如果您使用的是PostgreSQL,您还可以使用date\u trunc函数(为了可读性而拆分行,但在真正的Ruby中可能无法工作):
基本上,它会截断或删除日期中不再重要的部分。例如,如果选择“月”,它仍会保留年份和月份,但不保留日期和时间
我可能也会这样点:
Table.select('count(id), date_trunc('month', created_at) as month')
.where('published_state LIKE ?', 'published').group('month')
.order('month' DESC)
.limit(24)
阅读文档中的更多内容。是的,实际上,有一种方法可以在每个结果中包含id?
Table.select('count(id), date_trunc('month', created_at) as month')
.where('published_state LIKE ?', 'published').group('month')
.order('month' DESC)
.limit(24)