Oracle listagg, wm_concat function row-to-column results deduplication Oracle 11g/19c version

1. Prepare the data table

2. Group according to the student name (stu_name). If the student name is the same, the student age (stu_age) is spliced ​​with commas and spliced ​​using the listagg() function method

 

 3. There are two 12 and 12 in the above picture to realize deduplication

 3.1 listagg() function deduplication

[Method 1] Use regular expressions to deduplicate, both oracle 11g and oracle 19c are applicable

select
stu_name, 
regexp_replace(listagg(stu_age,',') within group (order by stu_age),
'([^,]+)(,\1)*(,|$)','\1\3') stu_age
from student group by stu_name

[Method 2] First deduplicate the data and use the listagg() function, both oracle 11g and oracle 19c are applicable 

select
stu_name, 
listagg(stu_age,',') within group (order by stu_age) stu_age
from (select DISTINCT stu_name,stu_age from student) 
group by stu_name

 [Method 3] Directly use the distinct method of the listagg( ) function, applicable to oracle 19c but not applicable to oracle 11g

select
stu_name, 
listagg(DISTINCT stu_age,',') within group (order by stu_age) stu_age
from student
group by stu_name

 

 [Method 3 simplification]: oracle 19c does not need to write within group (order by xxx), if you need to sort the deduplication results, you can add

select
stu_name, 
listagg(DISTINCT stu_age,',') stu_age
from student
group by stu_name

 3.2 wm_concat() function deduplication 

 [Method 1] Directly use the distinct method of the wm_concat( ) function, applicable to oracle 11g but not applicable to oracle 19c

select
stu_name, 
wm_concat(DISTINCT stu_age) stu_age
from student
group by stu_name

Using Oracle 19c to test the wm_concat() function will report an error

 Summary: Try to use the listagg function and avoid using wm_concat. The WM_CONCAT function has been deprecated in versions after 11gr2. Use the listagg function instead of wm_concat

Guess you like

Origin blog.csdn.net/SUMMERENT/article/details/129397722