Rails:如何为Datetime字段分组具有相同日期(月日年)的记录?

时间:2020-12-15 19:42:51

I have a Purchase model and I want to group all of the records by their ordered_datetime field. However, I don't care about the time, I just want to group by the date. So if there are 2 orders ordered on:

我有一个购买模型,我想用它们的ordered_datetime字段对所有的记录进行分组。但是,我不在乎时间,我只是想按日期分组。如果有2个订单

  1. 5/12/2014 12:00PM
  2. 5/12/2014旧
  3. 5/12/2014 3:00PM
  4. 5/12/2014下午三点

They should be grouped together even though they happened at different times during the day.

即使在白天发生的不同时间,它们也应该聚集在一起。

Is there a way to do this? Purchase.uniq.pluck(:ordered_datetime) separates the 2 records into 2 groups since their times are different.

有办法吗?pulse (:ordered_datetime)将两个记录分为两组,因为它们的时间不同。

1 个解决方案

#1


3  

You can use the DATE function on the timestamp column:

您可以在时间戳列上使用日期函数:

Purchase.group('DATE(ordered_datetime)').count

Which returns each date with a purchase count.

返回带有购买计数的每个日期。

You can also sort the dates by adding an order clause:

您还可以通过添加订单条款对日期进行排序:

Purchase.group('DATE(ordered_datetime)').order('date_ordered_datetime').count

#1


3  

You can use the DATE function on the timestamp column:

您可以在时间戳列上使用日期函数:

Purchase.group('DATE(ordered_datetime)').count

Which returns each date with a purchase count.

返回带有购买计数的每个日期。

You can also sort the dates by adding an order clause:

您还可以通过添加订单条款对日期进行排序:

Purchase.group('DATE(ordered_datetime)').order('date_ordered_datetime').count