Home > Database > Mysql Tutorial > How to Concatenate Strings from a Grouped Field in PostgreSQL?

How to Concatenate Strings from a Grouped Field in PostgreSQL?

Linda Hamilton
Release: 2025-01-22 08:31:09
Original
364 people have browsed it

How to Concatenate Strings from a Grouped Field in PostgreSQL?

In PostgreSQL databases, it is a common requirement to group by a specific field and concatenate the value of another string field in each group. The implementation method depends on the PostgreSQL version.

PostgreSQL 9.0 and above

PostgreSQL 9.0 and above (since 2010) provides the string_agg(expression, delimiter) function for this purpose. To concatenate the strings in a string field named EMPLOYEE, you can use the following query:

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

You can also specify a ORDER BY clause in an aggregate expression to control the order in which values ​​are concatenated.

PostgreSQL version 8.4

PostgreSQL 8.4 introduced the array_agg(expression)aggregation function, which collects values ​​into an array. To get the concatenated string you can use the array_to_string() function:

SELECT company_id, array_to_string(array_agg(employee), ', ')
FROM mytable
GROUP BY company_id;
Copy after login

PostgreSQL 8.3 and earlier

Prior to PostgreSQL 8.4, there was no built-in aggregate function to concatenate strings. Custom aggregate functions can be created using the CREATE AGGREGATE statement:

CREATE AGGREGATE textcat_all(
  basetype    = text,
  sfunc       = textcat,
  stype       = text,
  initcond    = ''
);
Copy after login

This basic aggregate function simply concatenates all the strings in the group. You can also create a custom function that adds a separator between concatenated values, for example:

CREATE FUNCTION commacat(acc text, instr text) RETURNS text AS $$
  BEGIN
    IF acc IS NULL OR acc = '' THEN
      RETURN instr;
    ELSE
      RETURN acc || ', ' || instr;
    END IF;
  END;
$$ LANGUAGE plpgsql;
Copy after login

You can then use a custom aggregate function in a GROUP BY query to concatenate the strings:

SELECT company_id, textcat_all(commacat(NULL, employee)) AS concatenated_employees
FROM mytable
GROUP BY company_id;
Copy after login

The above is the detailed content of How to Concatenate Strings from a Grouped Field in PostgreSQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template