string_agg 与array_agg

string_agg

实例1

  • 数据
imos=# select res_id, res_name from test;
 res_id |    res_name
--------+----------------
      1 | Root
  10001 | EC_PAG
  10002 | EC_PAG_GUOBIAO
(3 rows)
  • 普通string_agg
imos=# select string_agg(res_name,';') from test;
         string_agg
----------------------------
 Root;EC_PAG;EC_PAG_GUOBIAO
(1 row)
  • 带有order by 的string_agg
imos=# select string_agg(res_name,';' order by res_name ) from test;
         string_agg
----------------------------
 EC_PAG;EC_PAG_GUOBIAO;Root
(1 row)

实例2

  • 数据
postgres=# create table test(id int,name varchar(20));
CREATE TABLE
postgres=# insert into test values(1,'a');
INSERT 0 1
postgres=# insert into test values(1,'b');
INSERT 0 1
postgres=# insert into test values(1,'c');
INSERT 0 1
postgres=# insert into test values(2,'d');
INSERT 0 1
postgres=# insert into test values(2,'e');
INSERT 0 1
postgres=# select * from test;
 id | name
----+------
  1 | a
  1 | b
  1 | c
  2 | d
  2 | e
(5 rows)

  • 不分组

postgres=# select string_agg(name,',') from test;
 string_agg
------------
 a,b,c,d,e
(1 row)
  • 分组
postgres=# select id ,  string_agg(name,',') from test group by id;
 id | string_agg
----+------------
  2 | d,e
  1 | a,b,c
(2 rows)

array_agg

imos=# select array_agg(res_name) from test;
ERROR:  could not find array type for data type imos_name
imos=#
imos=#
imos=#
imos=# select array_agg(res_name::varchar) from test;
          array_agg
------------------------------
 {Root,EC_PAG,EC_PAG_GUOBIAO}
(1 row)

imos=#
imos=# select array_agg(res_name::varchar order by res_name ) from test;
          array_agg
------------------------------
 {EC_PAG,EC_PAG_GUOBIAO,Root}
(1 row)

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值