Skip to content
Advertisement

Remove duplicate values from string in oracle

I have requirement where I have input data like

Col1 COl2 Col3
A1    2    B
A1    1    A
A1    3    B
B1    1    A
B2    2    B
B2    3    C
B4    4    C
B5    5    A
B6    6    B

Output Required:

Col1 COl2 Col3
A1    2    AB
A1    1    AB
A1    3    AB
B1    1    ABC
B2    2    ABC
B2    3    ABC
B4    4    ABC
B5    5    ABC
B6    6    ABC    

Solution Tried:

select col1,col2,listagg(col3,'') within group (order by col3) over(partition by col1)
from tab

Output of the query:

Col1 COl2 Col3
A1    2    ABB
A1    1    ABB
A1    3    ABB
B1    1    AABBCC
B2    2    AABBCC
B2    3    AABBCC
B4    4    AABBCC
B5    5    AABBCC
B6    6    AABBCC

Can someone help here in removing repeating alphabets.

Thanks

Advertisement

Answer

You can use a subquery:

select col1, col2,
       listagg(case when seqnum = 1 then col3 end, '') within group (order by col3) over (partition by col1)
from (select t.*,
             row_number() over (partition by col1, col3 order by col3) as seqnum
      from tab t
     ) t
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement