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

前端 未结 14 1403
北荒
北荒 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:46

    According to version PostgreSQL 9.0 and above you can use the aggregate function called string_agg. Your new SQL should look something like this:

    SELECT company_id, string_agg(employee, ', ')
        FROM mytable GROUP BY company_id;
    
    0 讨论(0)
  • 2020-11-22 02:47

    You can also use format function. Which can also implicitly take care of type conversion of text, int, etc by itself.

    create or replace function concat_return_row_count(tbl_name text, column_name text, value int)
    returns integer as $row_count$
    declare
    total integer;
    begin
        EXECUTE format('select count(*) from %s WHERE %s = %s', tbl_name, column_name, value) INTO total;
        return total;
    end;
    $row_count$ language plpgsql;
    
    
    postgres=# select concat_return_row_count('tbl_name','column_name',2); --2 is the value
    
    0 讨论(0)
  • 2020-11-22 02:48

    How about using Postgres built-in array functions? At least on 8.4 this works out of the box:

    SELECT company_id, array_to_string(array_agg(employee), ',')
    FROM mytable
    GROUP BY company_id;
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-11-22 03:00

    Use STRING_AGG function for PostgreSQL and Google BigQuery SQL:

    SELECT company_id, STRING_AGG(employee, ', ')
    FROM employees
    GROUP BY company_id;
    
    0 讨论(0)
  • 2020-11-22 03:03

    As from PostgreSQL 9.0 you can use the aggregate function called string_agg. Your new SQL should look something like this:

    SELECT company_id, string_agg(employee, ', ')
    FROM mytable
    GROUP BY company_id;

    0 讨论(0)
提交回复
热议问题