I have a query which result is: (EDIT: 13.06.2023 12:30)
|ID|USER_NAME |
|--|--------------------|
|1 |A1,A1,A1,B12,B12,C32|
|2 |A1 |
|3 |B12,C32 |
Query for the above result:
SELECT
ID,
LISTAGG (user_name, ',') WITHIN GROUP (ORDER BY user_name )
From my_table
GROUP BY ID;
What I have tried to replace ',' with '|' and remove the duplicates and trim the last delimiter is:
SELECT
ID,
RTRIM(REGEXP_REPLACE(LISTAGG (user_name, ',') WITHIN GROUP (ORDER BY user_name ), '([^,]+)(,|\1)+', '\1|'),'|')
From my_table
GROUP BY ID;
The output is:
|ID|USER_NAME |
|--|------------|
|1 |A1|2|B12|C32|
|2 |A1 |
|3 |B12|C32 |
EDIT:
The LISTAGG and REGEXP should be part of a longer query and not be a standalone SELECT (output of LISTAGG should be a column of a long query). The example should only show what output I want to have in the end.
The second value for user_name and ID 1 is not correct.
How can I get the correct values? What is wrong in the query?
Thank you.