2

I'm trying to group by Date(). I've got 3 records with the created_at column:

2011-12-03 08:00:24, 2011-12-03 08:12:10, 2011-12-04 09:00:00

I'd like to only group by year, month and day, regardless of time. So for the example above. It should only return two rows:

2011-12-03 and 2011-12-04

How should I go about this?

0

6 Answers 6

8
... group by date(date_time_column)
2

This should allow you to group by year month and day

 SELECT group_by_column
      , DATE_FORMAT(created_at, '%Y')
      , DATE_FORMAT(created_at, '%m')
      , DATE_FORMAT(created_at, '%d')
   FROM my_table
  GROUP BY group_by_column

or if you want to do them all together.

 SELECT group_by_column
      , DATE_FORMAT(created_at, '%Y%m%d')
   FROM my_table
  GROUP BY group_by_column
1
  • 1
    In Rails 3, AR: Foobar.group('DATE_FORMAT(created_at, "%Y%m%d")'). Thanks for that Dec 4, 2011 at 14:16
2

Did you try the following?

SELECT 
    DATE(created_at) AS created_date 
FROM 
    my_table 
GROUP BY 
    created_date
1
2

MySQL permits GROUP BY DATE(created_at). So that would translate in ActiveRecord to .group(DATE(created_at))

In fact, that exact example is available in the Rails Guides on ActiveRecord querying.

2

You can use the Date() function.
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date

mysql> SELECT DATE('2003-12-31 01:02:03');
        -> '2003-12-31'
1

TRY

   GROUP BY DATE(`date_column`)

Reference

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.