Postgresql - concat_ws 之类的函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1943433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Postgresql - concat_ws like function?
提问by Gzorg
I'm having a first painful experience with postgresql, and the minute-challenge of the moment is :
我第一次使用 postgresql 时遇到了痛苦的经历,当下的小挑战是:
How to perform a concat_wsin postgresql, to join several fields value from a group by :
如何在 postgresql 中执行concat_ws,以通过以下方式加入组中的多个字段值:
select concat_ws(';',field_lambda) from table_lambda group by id;
回答by Milen A. Radev
For PostgreSQL 8.4 and above:
对于 PostgreSQL 8.4 及更高版本:
select ARRAY_TO_STRING(
ARRAY_AGG(field_lambda),';'
) from table_lambda group by id;
回答by Erwin Brandstetter
Since PostgreSQL 9.0(released September 2010), there is the aggregate function
string_agg()
to do what you seem to want:
自 PostgreSQL 9.0(2010 年 9 月发布)以来,有聚合函数
string_agg()
可以执行您似乎想要的操作:
SELECT string_agg(field1, ';') FROM tbl GROUP BY id;
Note, that the second parameter is the separator (similar to other aggregate functions) .
请注意,第二个参数是分隔符(类似于其他聚合函数)。
There is also the string function concat_ws()
since PostgreSQL 9.1, that's otherwise doing the same as MySQL's concat_ws()
(when not abused as aggregate function). It's particularly useful to deal with NULL
values.
concat_ws()
自 PostgreSQL 9.1起还有 string 函数,否则与 MySQL 的concat_ws()
功能相同(当未作为聚合函数滥用时)。处理NULL
值特别有用。
SELECT concat_ws(';', field1, field2, field3) FROM tbl
You could even combine both to aggreagate multiple columns any way you want.
您甚至可以将两者结合起来以任何您想要的方式聚合多个列。
SELECT id, string_agg(concat_ws(',', field1, field2, field3), ';') AS fields
FROM tbl
GROUP BY id;
回答by Daniel Vérité
Without array_agg
(before 8.4), you can use:
没有array_agg
(在 8.4 之前),您可以使用:
SELECT array_to_string(
ARRAY(SELECT field_lambda FROM table_lambda GROUP BY id), ';'
);
回答by nookni
According to PostgreSQL wiki, you can emulate the PostgreSQL 8.4 array_agg
function to get close to what you need.
根据PostgreSQL wiki,您可以模拟 PostgreSQL 8.4array_agg
函数以接近您需要的功能。
CREATE AGGREGATE array_agg(anyelement) (
SFUNC=array_append,
STYPE=anyarray,
INITCOND='{}'
);
回答by qaniel
Further people coming here for this problem, this method would not work with multiple columns(like concat_ws would) if you want to support multiple colums use
更多的人来这里解决这个问题,如果你想支持多列使用,这种方法不适用于多列(就像 concat_ws 一样)
ARRAY_TO_STRING(ARRAY[$columns_string], 'my_delimiter').