【问题标题】:Concatenate all the string values returned by distinct()连接 distinct() 返回的所有字符串值
【发布时间】:2019-11-07 17:16:15
【问题描述】:

以下答案的更新/注释 我的目标列上的pg_typeof() 是“regtype”,而不是“text”...

所以下面的人为例子是一个红鲱鱼。下面的@richyen 正确回答了它。对于那些表格不是文本的人,需要转换为文本,这是下面@a_horse_with_no_name 接受的答案


来自表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

但它不起作用。我哪里错了?提前致谢。

【问题讨论】:

  • 您的表被称为thing 并且您还有一个名为thing 的列,这有点令人困惑
  • @richyen ^谢谢。固定的。这是我为了说明我的问题而编造的一个通用示例。

标签: sql postgresql string-aggregation


【解决方案1】:

我认为您应该使用string_agg(),并带有distinct 子句:

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 或给定的模式是否需要一些特殊的东西才能使其工作?我应该接受答案吗?它回答了提出的问题......
  • 这取决于你。也许你在color 列中有一个奇怪的数据类型,你可以这样做string_agg(distinct color::text, ',')
  • 也许您可以使用您的实际架构更新您的帖子,以便我们帮助您诊断它?
【解决方案2】:

用户string_agg()

select string_agg(distinct color::text, ',') as colors
from thing

在线示例:https://rextester.com/GLFXG32756

【讨论】:

  • 给出错误:function string_agg(myschema.color, unknown) does not exist
  • 你试过...FROM myschema.thing吗?
  • @yen -- 你能用SELECT pg_typeof(color) FROM myschema.thing更新吗?
  • @yen:不要在列名前加上模式名。完全按照我展示的方式使用它。该代码当然有效:rextester.com/GLFXG32756
  • @yen:然后将其转换为text
猜你喜欢
  • 2012-10-07
  • 2021-10-01
  • 1970-01-01
  • 2011-09-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-03
相关资源
最近更新 更多