连接 distinct() 返回的所有字符串值
Concatenate all the string values returned by distinct()
更新/注意以下答案
pg_typeof()
在我的目标列上是 "regtype",而不是 "text"...
所以下面这个人为的例子是一条红鲱鱼。下面的@richyen 正确回答了这个问题。对于那些 table 不是文本的人,需要转换为文本,这是下面
@a_horse_with_no_name 接受的答案
来自 table myschema.thing
:
id | fruit | color | owner_id
---+--------+--------+---------
1 | apple | red | 100
2 | banana | yellow | 100
3 | tomato | red | 500
4 | grape | purple | 200
我正在尝试获取结果:
colors
------------------
red,yellow,purple
基于此页面:https://www.postgresql.org/docs/11/functions-string.html
我试过这个:
select concat_ws(',', distinct(color)) as colors
from myschema.thing
但是没用。我哪里错了?提前致谢。
我认为你应该使用带有 distinct
子句的 string_agg()
:
postgres=# create table thing (id int, color text);
CREATE TABLE
postgres=# insert into thing values (1, 'red'),(2,'yellow'),(3,'red'),(4,'purple');
INSERT 0 4
postgres=# select * from thing;
id | color
----+--------
1 | red
2 | yellow
3 | red
4 | purple
(4 rows)
postgres=# select string_agg(distinct color, ',') as colors from myschema.thing;
colors
-------------------
purple,red,yellow
(1 row)
用户string_agg()
select string_agg(distinct color::text, ',') as colors
from thing
更新/注意以下答案
pg_typeof()
在我的目标列上是 "regtype",而不是 "text"...
所以下面这个人为的例子是一条红鲱鱼。下面的@richyen 正确回答了这个问题。对于那些 table 不是文本的人,需要转换为文本,这是下面
@a_horse_with_no_name 接受的答案来自 table myschema.thing
:
id | fruit | color | owner_id
---+--------+--------+---------
1 | apple | red | 100
2 | banana | yellow | 100
3 | tomato | red | 500
4 | grape | purple | 200
我正在尝试获取结果:
colors
------------------
red,yellow,purple
基于此页面:https://www.postgresql.org/docs/11/functions-string.html
我试过这个:
select concat_ws(',', distinct(color)) as colors
from myschema.thing
但是没用。我哪里错了?提前致谢。
我认为你应该使用带有 distinct
子句的 string_agg()
:
postgres=# create table thing (id int, color text);
CREATE TABLE
postgres=# insert into thing values (1, 'red'),(2,'yellow'),(3,'red'),(4,'purple');
INSERT 0 4
postgres=# select * from thing;
id | color
----+--------
1 | red
2 | yellow
3 | red
4 | purple
(4 rows)
postgres=# select string_agg(distinct color, ',') as colors from myschema.thing;
colors
-------------------
purple,red,yellow
(1 row)
用户string_agg()
select string_agg(distinct color::text, ',') as colors
from thing