PostgreSQL Data row value connection
]In relational database operations, it is often necessary to process the data before obtaining the final result. A common task is to concatenate values of multiple rows based on common identifiers. In PostgreSQL, the GROUP_CONCAT
function provides a simple solution for this.
GROUP_CONCAT
FunctionPostgreSQL version 9.0 and above introduces the GROUP_CONCAT
aggregate function, which takes a set of values in a column and concatenates them into a single string. GROUP_CONCAT
syntax is as follows:
GROUP_CONCAT(DISTINCT expression [ORDER BY expression] [separator])
parameter:
Consider the following table called "sample_data":
id | value |
---|---|
TM67 | 4 |
TM67 | 9 |
TM67 | 72 |
TM99 | |
TM99 |
SELECT id, GROUP_CONCAT(value) AS concatenated_values
FROM sample_data
GROUP BY id;
SELECT id, GROUP_CONCAT(value) AS concatenated_values FROM sample_data GROUP BY id;
id | |
---|---|
TM67 | |
TM99 |
]
As you can see, the values of each "id" are concatenated and separated by commas.
SELECT id, string_agg(value, ',') AS concatenated_values
FROM sample_data
GROUP BY id;
:
SELECT id, string_agg(value, ',') AS concatenated_values
FROM sample_data
GROUP BY id;
GROUP_CONCAT syntax described above.
in conclusion
GROUP_CONCAT or the
functions, you can easily concatenate multi-row data in PostgreSQL. Which syntax to choose depends on your PostgreSQL version and personal preferences.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3