Is there a built in function for comma separated column values in DB2 SQL
?
Example: If there are columns with an ID
and it has 3 rows with the same ID
but have three different roles, the data should be concatenated with a comma.
ID | Role ------------ 4555 | 2 4555 | 3 4555 | 4
The output should look like the following, per row:
4555 2,3,4
In order to fetch the comma separated (delimited) values from the Stored Procedure, you need to make use of a variable with data type and size same as the Output parameter and pass it as Output parameter using OUTPUT keyword.
The LISTAGG function aggregates a set of string values for a group into one string by appending the string-expression values based on the order that is specified in the WITHIN GROUP clause. The function is applied to the set of values that are derived from the first argument by the elimination of null values.
LISTAGG function is new function in DB2 LUW 9.7
see example:
create table myTable (id int, category int); insert into myTable values (1, 1); insert into myTable values (2, 2); insert into myTable values (5, 1); insert into myTable values (3, 1); insert into myTable values (4, 2);
example: select without any order in grouped column
select category, LISTAGG(id, ', ') as ids from myTable group by category;
result:
CATEGORY IDS --------- ----- 1 1, 5, 3 2 2, 4
example: select with order by clause in grouped column
select category, LISTAGG(id, ', ') WITHIN GROUP(ORDER BY id ASC) as ids from myTable group by category;
result:
CATEGORY IDS --------- ----- 1 1, 3, 5 2 2, 4
I think with this smaller query, you can do what you want. This is equivalent of MySQL's GROUP_CONCAT in DB2.
SELECT NUM, SUBSTR(xmlserialize(xmlagg(xmltext(CONCAT( ', ',ROLES))) as VARCHAR(1024)), 3) as ROLES FROM mytable GROUP BY NUM;
This will output something like:
NUM ROLES ---- ------------- 1 111, 333, 555 2 222, 444
assumming your original result was something like that:
NUM ROLES ---- --------- 1 111 2 222 1 333 2 444 1 555
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With