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

前端 未结 14 1737
北荒
北荒 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 03:11

    As already mentioned, creating your own aggregate function is the right thing to do. Here is my concatenation aggregate function (you can find details in French):

    CREATE OR REPLACE FUNCTION concat2(text, text) RETURNS text AS '
        SELECT CASE WHEN $1 IS NULL OR $1 = \'\' THEN $2
                WHEN $2 IS NULL OR $2 = \'\' THEN $1
                ELSE $1 || \' / \' || $2
                END; 
    '
     LANGUAGE SQL;
    
    CREATE AGGREGATE concatenate (
      sfunc = concat2,
      basetype = text,
      stype = text,
      initcond = ''
    

    );

    And then use it as:

    SELECT company_id, concatenate(employee) AS employees FROM ...
    

提交回复
热议问题