• 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)
    
    
  • 相关阅读:
    SpringBoot @Transactional声明事务无效问题
    高并发秒杀系统方案(集成Mybatis和Redis)
    高并发秒杀系统方案(项目框架搭建)
    高并发秒杀系统方案(简介)
    解决VMware虚拟机的CentOS无法上网
    收货地址管理模块开发
    购物车模块开发
    乐观锁和悲观锁
    商品模块开发
    数据库系列学习(十)-约束
  • 原文地址:https://www.cnblogs.com/yldf/p/11899976.html
Copyright © 2020-2023  润新知