How to get inbuilt function for comma separated column values in sql in DB2 , e.g if there are columns with this policy id and it has 3 rows with the same id but have three different roles in three rows , then it should retrieve the rows in one row "3,4,5"
e.g.
1. 4555 "2"
2. 4555 "3"
3. 4555 "4"
output 4555 2,3,4
in a DB2 in one row
Depending of the DB2 version you have, you can use XML functions to achieve this.
Example table with some data
Aggregate results using xml functions
results:
Use replace to make the result look better
Cleaned result
Just saw a better solution using XMLTEXT instead of XMLELEMENT here.
LISTAGG function is new function in DB2 LUW 9.7
see example:
example: select without any order in grouped column
result:
example: select with order by clause in grouped column
result:
Try this:
My problem was to transpose row fields(CLOB) to column(VARCHAR) with a CSV and use the transposed table for reporting. Because transposing on report layer slows down the report.
One way to go is to use recursive SQL. You can find many articles about that but its difficult and resource consuming if you want to join all your recursive transposed columns.
I created multiple global temp tables where I stored single transposed columns with one key identifier. Eventually, I had 6 temp tables for joining 6 columns but due to limited resource allocation I wasnt able to bring all columns together. I opted to below 3 formulas and then I just had to run 1 query which gave me output in 10 seconds.
I found various articles on using XML2CLOB functions and have found 3 different ways.
Make sure you are casting your "ATTRIBUTENAME" to varchar in a subquery and then calling it here.
other possibility, with recursive cte
Since DB2 9.7.5 there is a function for that:
LISTAGG(colname, separator)
check this for more information: Using LISTAGG to Turn Rows of Data into a Comma Separated List