Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何统计日期范围内每天的记录_Ruby On Rails_Ruby_Postgresql 9.2 - Fatal编程技术网

Ruby on rails 如何统计日期范围内每天的记录

Ruby on rails 如何统计日期范围内每天的记录,ruby-on-rails,ruby,postgresql-9.2,Ruby On Rails,Ruby,Postgresql 9.2,我有投票系统。每次投票都有一个分数 我想数一数每天投了多少票 下面的代码将每天的每次投票的分数相加,并返回一个哈希值,其中包含总数和日期作为关键字: 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,

我有投票系统。每次投票都有一个分数

我想数一数每天投了多少票

下面的代码将每天的每次投票的分数相加,并返回一个哈希值,其中包含总数和日期作为关键字:

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

我想数一数每天有多少人投票。有什么想法吗?

相应的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])

您可以使用更好的语法执行您想要的操作:

from = start.beginning_of_day
to   = Time.zone.now
Rating.group('date(created_at)').where(created_at: from .. to).count(:score)
这将返回一个散列,其中日期(created_at)作为关键字,计数(:score)作为每天的值

例如: {“2014-01-21”=>100,“2014-01-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)

哦,我没有注意到日期范围,让我在一分钟内更正答案。这个问题有标签
postgresql-9.2
@Monk_代码查询看起来也可以在Pg中运行。你只需修复标识符的奇怪引用,删除
评级周围的反勾,或者用ANSI SQL标准双引号替换它们(
“评级”
)我需要计数而不是求和?在你的问题中,你使用了求和。我将把答案改为使用计数。