2014-01-24 88 views
4

我有投票系统。每个投票都有一个分数。如何统计日期范围内的每一天的记录

我想能够统计每天有多少票?

下面的代码添加的每票每一天的成绩,并返回总哈希和日期作为重点:

ratings = where(created_at: start.beginning_of_day..Time.zone.now).group("created_at").select("created_at, sum(score) as total_score") 
ratings.each_with_object({}) do |rating, scores| 
scores[rating.created_at.to_date] = rating.total_score 
end 

我希望能算多少票作了关于每天。有任何想法吗?

回答

0

相应的MySQL查询将

SELECT date(created_at) as date, count(*) as count FROM `ratings` WHERE (created_at between '2014-01-21 00:00:00' AND '2014-01-24 08:16:46') GROUP BY date(created_at) 

Rails的版本是:

start_date = Date.parse("2014-01-21").beginning_of_day 
end_time = Time.zone.now 
Rating.group('date(created_at)').select('date(created_at) as date, count(*) as count').where(["created_at between ? AND ?", start_time, end_time]) 
+0

噢,我没有” t注意日期范围,lemme正确答案在一分钟 –

+0

这个问题有标签'postgresql-9.2' –

+0

@Monk_Code查询看起来像它会在Pg运行也很好,你只需要修复奇怪的屁股MySQL引用的标识符,去掉'rating'附近的反引号或用ANSI SQL标准双引号替换它们('“ratings”') –

10

你可以做你想要使用哪一个更漂亮的语法:

from = start.beginning_of_day 
to = Time.zone.now 
Rating.group('date(created_at)').where(created_at: from .. to).count(:score) 

这将每天返回一个包含日期(created_at)作为键和计数(:分数)作为值的散列。

实施例: { “2014年1月21日”=> 100 “2014年1月22日”=> 1213}

相应的SQL是:

SELECT COUNT("ratings"."score") AS count_score, date(created_at) AS date_created_at FROM "ratings" WHERE ("ratings"."created_at" BETWEEN '2014-01-21' AND '2014-01-24') GROUP BY date(created_at) 
+0

我需要计数,而不是总结? – grabury

+0

在你的问题中你使用了sum。我会改变使用计数的答案。 – cristian

相关问题