PostgreSQL中按指定列分组
也许,这个问题有点愚蠢,但我很困惑。
如何按指定列对记录进行分组? :)
Item.group(:category_id)
不起作用...
它说:
ActiveRecord::StatementInvalid: PGError: 错误: 列“items.id”必须出现在 GROUP BY 子句中或在聚合函数中使用 第 1 行:按类别_id 从“项目”组中选择“项目”。*
我应该使用哪种聚合函数?
请您提供一个简单的例子。
Maybe, this question is a little stupid, but I'm confused.
How to group records by specified column ? :)
Item.group(:category_id)
does't works...
It says:
ActiveRecord::StatementInvalid: PGError: ERROR: column "items.id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT "items".* FROM "items" GROUP BY category_id
What kind of aggregate function should i use?
Please, could you provide a simple example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须定义如何对共享相同
category_id
的值进行分组。将它们连接起来?计算总和?要创建以逗号分隔的值列表,您的语句可能如下所示:
You need Postgres 9.0 or later for
string_agg(col1, ', ')
。在旧版本中,您可以用 array_to_string(array_agg(col1), ', ') 替换。更多聚合函数此处。
与在客户端中聚合值相比,在 PostgreSQL 中聚合值显然是更好的方法。 Postgres 在这方面非常快并且减少了(网络)流量。
You will have to define, how to group values that share the same
category_id
. Concatenate them? Calculate a sum?To create comma-separated lists of values your statement could look like this:
You need Postgres 9.0 or later for
string_agg(col1, ', ')
.In older versions you can substitute with
array_to_string(array_agg(col1), ', ')
. More aggregate functions here.To aggregate values in PostgreSQL is the clearly superior approach as opposed to aggregating values in the client. Postgres is very fast at this and it reduces (network) traffic.
您可以使用
sum
、avg
、count
或任何其他聚合函数。有关此主题的更多信息,您可以在此处找到。但看来你真的不需要使用SQL分组。
尝试获取所有记录,然后使用
Array#collect
函数按category_id
对Item
进行分组You can use
sum
,avg
,count
or any other aggregate function. More on this topic you can find here.But it seems that you don't really need to use SQL grouping.
Try to fetch all records and then use
Array#collect
function to groupItem
s bycategory_id
SQL 中的分组意味着服务器将数据库表中的一个或多个记录分组到一个结果行中。因此,如果您按
category_id
进行分组,则可能有多个与给定类别匹配的记录,因此您不能期望数据库返回表中的所有列(这就是SELECT *
实际所做的)。相反,当您使用
GROUP BY
时,您只能SELECT
:根据您的具体需要,相应地修改您的
.select
。Grouping in SQL means that the server groups one or more records from the database table into one resulting row. So, if you for example group by
category_id
, you might have several records matching the given category, so you can't expect the database to return all columns from the table (that's whatSELECT *
actually does).Instead, when you use
GROUP BY
, you canSELECT
only:Depending on what you exactly need, modify your
.select
accordingly.