How can I eliminate duplicate data in column

痞子三分冷 提交于 2019-12-24 00:39:11

问题


I would like to eliminate duplicates and show one time

for example

SELECT 'apple, apple, orange'
FROM dual;

I would like to show

apple, orange

as another example.

SELECT 'apple, apple, apple, apple,'
FROM dual;

I just want to show

apple

This code shows

with data as
(
  select 'apple, apple, apple, apple' col from dual
)
select listagg(col, ',') within group(order by 1) col
  from (
        select distinct regexp_substr(col, '[^,]+', 1, level) col
          from data
        connect by level <= regexp_count(col, ',')
       )

回答1:


Something like this will eliminate duplicates:

SQL Demo

with temp as
(
    select 1 Name, 'test1' Project, 'apple, apple, orange' Error  from dual
    union all
    select 2, 'test2', 'apple, apple, apple, apple,' from dual
), split as (
    select distinct
      t.name, t.project,
      trim(regexp_substr(t.error, '[^,]+', 1, levels.column_value))  as error
    from 
      temp t,
      table(cast(multiset(select level 
                          from dual connect by  level <= length (regexp_replace(t.error, '[^,]+'))  + 1) as sys.OdciNumberList)) levels
)
SELECT Name, listagg(Error, ',') within group(order by 1) as result 
FROM split
GROUP BY Name

OUTPUT

As you can see you get a NULL because that extra comma ,




回答2:


There are several options in Oracle forum as:

with data as
 (
 select 

'5,5,5,5,6,6,5,5,5,6,7,4,1,2,1,4,7,2' col from dual
)
 select listagg(col, ',') within group(order by 1) col
 from (
    select distinct regexp_substr(col, '[^,]+', 1, level) col
    from data
    connect by level <= regexp_count(col, ',')
   )

Just replace the numbers with input as 'apple, apple, orange'




回答3:


Using trim and distinct with regexp functions is very important to get the desired result as

select listagg(str,',') within group (order by 0) as Result
from
(
 select distinct trim(regexp_substr('apple, apple, orange','[^,]+', 1, level)) as str
   from dual
connect by level <= regexp_count('apple, apple, orange',',') + 1
);

Rextester Demo



来源:https://stackoverflow.com/questions/53377436/how-can-i-eliminate-duplicate-data-in-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!