How does PostgreSQL implement group_concat?

Source: Internet
Author: User
MySQL has a clustering function group_concat, which can concatenate fields by group ID, such

Table:
ID name
---------------
1
2 B
1 B

Select ID, group_concat (name) from XXX group by ID
The result is

Id group_concat (name)
---------------------------
1 A, B
2 B

PostgreSQL does not have a ready-made group_concat clustering function, but it can be customized to implement this function easily.

Custom clustering function group_concat

Create aggregate group_concat (anyelement)
(
Sfunc = array_append, -- the operation function of each row, append the row to the array
Stype = anyarray, -- returns the array type after aggregation
Initcond = '{}' -- Initialize an empty array
);

The anyelement parameter matches any type and returns the array type anyarray after aggregation. This function is used to append records of each row to the array.

Select ID, group_concat (name) from XXX group by ID
The result is

Id array_accum (name)
---------------------------
1 {'A', 'B '}
2 {'B '}

Array_accum (name) is an array type. Then, use the array_to_string function to convert the array to a string.

Select ID, array_to_string (group_concat (name), ',') from XXX group by ID
You can get the same group_concat result.

However, the group_concat function of MySQL is very powerful, such as sorting. To simulate it in PostgreSQL, you can only define an enhanced function, such as array_to_string_plus. You can sort the array before Concat, I don't need to talk about it here. I will leave it to you.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.