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.