How to concatenate strings of a string field in a PostgreSQL 'group by' query?

前端 未结 14 1600
北荒
北荒 2020-11-22 02:37

I am looking for a way to concatenate the strings of a field within a group by query. So for example, I have a table:

ID   COMPANY_ID   EMPLOYEE
1    1               


        
14条回答
  •  一向
    一向 (楼主)
    2020-11-22 02:59

    I claim no credit for the answer because I found it after some searching:

    What I didn't know is that PostgreSQL allows you to define your own aggregate functions with CREATE AGGREGATE

    This post on the PostgreSQL list shows how trivial it is to create a function to do what's required:

    CREATE AGGREGATE textcat_all(
      basetype    = text,
      sfunc       = textcat,
      stype       = text,
      initcond    = ''
    );
    
    SELECT company_id, textcat_all(employee || ', ')
    FROM mytable
    GROUP BY company_id;
    

提交回复
热议问题