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

前端 未结 14 1423
北荒
北荒 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 ...
    
    0 讨论(0)
  • 2020-11-22 03:12

    I'm using Jetbrains Rider and it was a hassle copying the results from above examples to re-execute because it seemed to wrap it all in JSON. This joins them into a single statement that was easier to run

    select string_agg('drop table if exists "' || tablename || '" cascade', ';') 
    from pg_tables where schemaname != $$pg_catalog$$ and tableName like $$rm_%$$
    
    0 讨论(0)
提交回复
热议问题