如何在PostgreSQL中将列值转换为单行值

时间:2019-12-12 23:55:52

标签: sql arrays postgresql

数据

  id      cust_name

  1        walmart_ca
  2        ikea_mo
  2        ikea_ca
  2        ikea_in
  1        walmart_in

当我这样做

  select id,cust_name from test where id=2 

查询在输出下方返回

   id  cust_name

    2  ikea_mo
    2  ikea_ca
    2  ikea_in

如何获取结果或将其存储为单列值,如下所示

    id   cust_name

     2   {ikea_mo,ikea_ca,ikea_in}

1 个答案:

答案 0 :(得分:1)

您应该使用string_agg函数,这是一个示例

select  string_agg(field_1,',') from db.schema.table;

在您的情况下,您应该提到分隔符,,所以我在做string_agg(field_1,',')