Several time i need to groups some values in one column and make it into one single column which separated by commas, for example when i have table category_product which is contains column productId, productName, and category. Foreach category of a product stored on a single row entry and each products can have more than one category. To select each product and its categories then make list of categories within single row for each product.
On complex way with create such a procedure thas has a loop and concate all category on a variable maybe can solved the problem. But yes.. it needs a time and more effort, so why we not use the easy way?
There is GROUP_CONCAT on MySQL or LISTAGG on Oracle that can group value from some column and group them by specific id into single strings.
GROUP_CONCAT on MySQL
Syntax:group_concat(column_name) or group_concat(column_name separator 'separator_type')
Example:
select id, group_concat(category) from table1 group by id;
select id, group_concat(category separator ';') from table1 group by id;
Note: Default separator on group_concat function is commas. Add "separator" after column name to change the separator.
LISTAGG on Oracle
Syntax:listagg(column_name, separator) within group (order by column_name)
over (partition by column_name)
Example:
select id, listagg(category, ',') within group (order by id) from table1 group by id;
select id, listagg(category, ',') within group (order by id) over (partition by id) from table1;
Note: Instead of group by use over(partition by ....) to groupping the result.
references:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions089.htm
