Postgresql GROUP_CONCAT 等价物? [英] Postgresql GROUP_CONCAT equivalent?
问题描述
我有一张表格,我想为每个 ID 拉出一行,并将字段值串联起来.
I have a table and I'd like to pull one row per id with field values concatenated.
例如,在我的表中,我有这个:
In my table, for example, I have this:
TM67 | 4 | 32556
TM67 | 9 | 98200
TM67 | 72 | 22300
TM99 | 2 | 23009
TM99 | 3 | 11200
我想输出:
TM67 | 4,9,72 | 32556,98200,22300
TM99 | 2,3 | 23009,11200
在 MySQL 中,我能够使用聚合函数 GROUP_CONCAT
,但这在这里似乎不起作用......是否有 PostgreSQL 的等效函数,或其他方法来实现此目的?>
In MySQL I was able to use the aggregate function GROUP_CONCAT
, but that doesn't seem to work here... Is there an equivalent for PostgreSQL, or another way to accomplish this?
推荐答案
这可能是一个很好的起点(仅限 8.4+ 版本):
This is probably a good starting point (version 8.4+ only):
SELECT id_field, array_agg(value_field1), array_agg(value_field2)
FROM data_table
GROUP BY id_field
array_agg 返回一个数组,但您可以对其进行 CAST文本并根据需要进行编辑(请参阅下面的说明).
array_agg returns an array, but you can CAST that to text and edit as needed (see clarifications, below).
在 8.4 版本之前,您必须在使用前自己定义它:
Prior to version 8.4, you have to define it yourself prior to use:
CREATE AGGREGATE array_agg (anyelement)
(
sfunc = array_append,
stype = anyarray,
initcond = '{}'
);
(转述自 PostgreSQL 文档)
(paraphrased from the PostgreSQL documentation)
说明:
- 将数组转换为文本的结果是生成的字符串以花括号开头和结尾.如果不需要的话,需要通过某种方法移除这些大括号.
- 将 ANYARRAY 转换为 TEXT 可以最好地模拟 CSV 输出,因为包含嵌入逗号的元素在标准 CSV 样式的输出中被双引号引用.array_to_string() 或 string_agg()(9.1 中添加的group_concat"函数)都没有引用嵌入逗号的字符串,导致结果列表中的元素数量不正确.
- 新的 9.1 string_agg() 函数不会先将内部结果转换为 TEXT.因此,如果 value_field 是整数,string_agg(value_field)"会产生错误.string_agg(value_field::text)"是必需的.array_agg() 方法只需要在聚合后进行一次强制转换(而不是对每个值进行一次强制转换).
这篇关于Postgresql GROUP_CONCAT 等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!