Home > Database > Mysql Tutorial > How to Concatenate Field Values in PostgreSQL?

How to Concatenate Field Values in PostgreSQL?

Susan Sarandon
Release: 2025-01-21 09:27:09
Original
403 people have browsed it

How to Concatenate Field Values in PostgreSQL?

Join field values ​​in PostgreSQL

In some database applications, it is necessary to retrieve a single row for each unique identifier from the table and concatenate the corresponding field values. For example, given a table containing the following data:

ID 列A 列B
TM67 4 32556
TM67 9 98200
TM67 72 22300
TM99 2 23009
TM99 3 11200

The expected output is as follows:

ID 列A 列B
TM67 4,9,72 32556,98200,22300
TM99 2,3 23009,11200

In MySQL, the GROUP_CONCAT aggregate function is usually used to achieve this purpose. However, there is no direct equivalent in PostgreSQL.

Fortunately, PostgreSQL provides some alternative mechanisms to achieve the same result:

<code class="language-sql">SELECT id, 
       string_agg(some_column, ',')
FROM the_table
GROUP BY id</code>
Copy after login

This method uses the string_agg function (introduced in PostgreSQL 9.0) to aggregate the values ​​of the specified column into a comma-delimited string. The GROUP BY clause ensures that the aggregation operation is performed separately for each unique ID.

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

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template