Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I group by day instead of date?

ok so i have

 >> list = Request.find_all_by_artist("someBand")
=> [#<Request id: 1, artist: "someBand", song: "someSong", venue: "Knebworth - Stevenage, United Kingdom", showdate: "2011-07-01", amount: nil, user_id: 2, created_at: "2011-01-01 18:14:08", updated_at: "2011-01-01 18:14:09".............

and then

list.group_by(&:created_at).map {|k,v| [k, v.length]}.sort
=> [[Sat, 01 Jan 2011 18:14:08 UTC +00:00, 10], [Sun, 09 Jan 2011 18:34:19 UTC +00:00, 1], [Sun, 09 Jan 2011 18:38:48 UTC +00:00, 1], [Sun, 09 Jan 2011 18:51:10 UTC +00:00, 1], [Sun, 09 Jan 2011 18:52:30 UTC +00:00, 1], [Thu, 10 Feb 2011 02:22:08 UTC +00:00, 1], [Thu, 10 Feb 2011 20:02:20 UTC +00:00, 1]]

the problem is I have a few Sun, 09 Jan and a couple for the 10th, instead of one like this

this is what i need

=> [[Sat, 01 Jan 2011 18:14:08 UTC +00:00, 10], [Sun, 09 Jan 2011 18:34:19 UTC +00:00, 4], [Thu, 10 Feb 2011 20:02:20 UTC +00:00, 2]]
like image 829
Matt Elhotiby Avatar asked Feb 13 '11 22:02

Matt Elhotiby


People also ask

How do I group data by day of the week in SQL?

How Do You Group Data by Week in SQL Server? SQL Server provides a function called DATEPART() , which returns a specified part (year, quarter, month, week, hour, minute, etc.) of a specified date. ORDER BY DATEPART(week, RegistrationDate);

How do you GROUP BY a date and count in SQL?

1 Answer. You can use DATE_FORMAT operator. If you are using this you can easily group the date, timestamp or datetime column using whatever format you want.

How do I Group A timestamp by month?

You can group month and year with the help of function DATE_FORMAT() in MySQL. The GROUP BY clause is also used.


2 Answers

I think this is a much more elegant and simple solution

list.group_by{|x| x.created_at.strftime("%Y-%m-%d")} 
like image 137
Fellps Avatar answered Oct 09 '22 02:10

Fellps


Time is a quite complex object to group by. Assuming you want to group by the creation date, instead of the full Time, start creating a custom method in your model to return the group criteria.

The method should return the creation date, possibly as string.

def group_by_criteria
  created_at.to_date.to_s(:db)
end

Then, group by that method.

list.group_by(&:group_by_criteria).map {|k,v| [k, v.length]}.sort
like image 36
Simone Carletti Avatar answered Oct 09 '22 01:10

Simone Carletti