在ActiveRecord中按created_at分组记录

时间:2022-10-04 12:13:46

I'm trying to find how many records were created on a given day, to get something like this:

我试图找到在给定的一天创建了多少记录,得到这样的东西:

User uploaded 5 objects two days ago

用户两天前上传了5个对象

User uploaded 12 objects 21 days ago

用户上传了12个对象21天前

I've tried:

我试过了:

Flight.group("created_at::date")

but get the error:

但得到错误:

ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  column "flights.id" must appear in the GROUP BY clause or be used in an aggregate function

but when I try adding the id either directly to the group field or by adding another .group I end up grouping on both the id and created_at, which obviously doesn't group anything since there would only be one instance of each match.

但是当我尝试将id直接添加到组字段或添加另一个.group时,我最终会对id和created_at进行分组,这显然不会对任何内容进行分组,因为每个匹配只有一个实例。

What am I missing here?

我在这里想念的是什么?

1 个解决方案

#1


1  

If you're trying to count things then count them:

如果你想要计算东西,那就算一下:

Flight.group('created_at::date').count

That will give you a hash with dates as keys and counts as values. Otherwise, the database won't know which values from the rows in the group should be used to represent the group. If you add the count aggregate function then the ambiguity is gone and the database knows what you want it to do.

这将为您提供一个哈希,其中日期为键,并计为值。否则,数据库将不知道应该使用组中的行中的哪些值来表示组。如果添加计数聚合函数,则模糊性消失,数据库知道您希望它做什么。

#1


1  

If you're trying to count things then count them:

如果你想要计算东西,那就算一下:

Flight.group('created_at::date').count

That will give you a hash with dates as keys and counts as values. Otherwise, the database won't know which values from the rows in the group should be used to represent the group. If you add the count aggregate function then the ambiguity is gone and the database knows what you want it to do.

这将为您提供一个哈希,其中日期为键,并计为值。否则,数据库将不知道应该使用组中的行中的哪些值来表示组。如果添加计数聚合函数,则模糊性消失,数据库知道您希望它做什么。