Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count records for each day in a date range

I have a voting system. Each vote has a score.

I want to be able to count how many votes were made per day?

The code below adds the scores of each vote for each day and returns a hash with the total and the date as a key:

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

I want to be able to count how many votes were made on each day. Any ideas?

like image 215
grabury Avatar asked Jan 24 '14 08:01

grabury


1 Answers

You can do what you want using a much nicer syntax:

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

This will return a hash having the date(created_at) as a key and count(:score) as value, for each day.

Example: { "2014-01-21" => 100, "2014-01-22" => 1213 }

The corresponding SQL is:

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)
like image 63
cristian Avatar answered Nov 15 '22 10:11

cristian