6

我正在尝试在 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 >]

我怎样才能做到这一点?

谢谢!

4

2 回答 2

16

尝试这个:

Table.where(:published_state => 'published').
  group('year(created_at)').group('month(created_at)').count(:id)

结果的格式不是我所期望的(它是一个带有数组键[year, month]和计数值的散列),但也许它会满足您的目的?

于 2013-05-30T17:51:08.883 回答
0

如果您使用的是 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)

在此处的文档中阅读更多信息。

于 2015-12-27T01:42:58.167 回答