按PostgreSQL中的指定列进行分组 [英] Group by specified column in PostgreSQL

查看:1140
本文介绍了按PostgreSQL中的指定列进行分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许,这个问题有点愚蠢,但我很困惑。

如何按指定列对记录进行分组? :)

  Item.group(:category_id)

does not work ...



它说:

< blockquote>

ActiveRecord :: StatementInvalid:PGError:ERROR:columnitems.id必须出现在GROUP BY子句中或用于聚合函数
LINE 1:SELECTitems。 * FROMitemsGROUP BY category_id


我应该使用什么样的聚合函数?



请提供一个简单的例子。

解决方案

您必须定义 / em>分组共享相同的 category_id 的值。连接它们?计算总和?



要创建以逗号分隔的值列表,您的语句可能如下所示:

  SELECT category_id 
,string_agg(col1,',')AS col1_list
,string_agg(col2,',')AS col2_list
FROM items
GROUP BY category_id

对于 string_agg(col1,',')
在旧版本中,您可以用 array_to_string(array_agg(col1),',')替代。更多集合函数此处



在PostgreSQL中聚合值是明显的优越方法,而不是在客户端聚合值。 Postgres在这方面非常快速,它可以减少(网络)流量。


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.

解决方案

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:

SELECT category_id
      ,string_agg(col1, ', ') AS col1_list
      ,string_agg(col2, ', ') AS col2_list
FROM   items
GROUP  BY category_id

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.

这篇关于按PostgreSQL中的指定列进行分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆