如何消除多列查询中的重复数据

时间:2018-11-19 15:54:53

标签: sql regex oracle oracle11g

我只是问了一个有关如何消除列中重复数据的问题

How can I eliminate duplicate data in column

下面的这段代码可以删除列中的重复项

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, ',')
       )

下一个问题是 现在我不知道如何消除多列数据

select 'apple, apple, apple' as col1, 
       'prince,prince,princess' as col2, 
       'dog, cat, cat' as col3
  from dual;

我想展示

COL1     COL2                COL3
-----    ----------------    --------
apple    prince, princess    dog, cat

1 个答案:

答案 0 :(得分:1)

您可以使用这样的组合:

select  
    (
    select listagg(str,',') within group (order by 0)
      from
     (
      select distinct trim(regexp_substr('apple, apple, apple','[^,]+', 1, level)) as str
        from dual
     connect by level <= regexp_count('apple, apple, apple',',') + 1
     )
    ) as str1,
    (
    select listagg(str,',') within group (order by 0)
      from
     (
      select distinct trim(regexp_substr('prince,prince,princess','[^,]+', 1, level)) as str
        from dual
     connect by level <= regexp_count('prince,prince,princess',',') + 1
     )
    ) as str2,   
    (
    select listagg(str,',') within group (order by 0)
      from
     (
      select distinct trim(regexp_substr('dog, cat, cat','[^,]+', 1, level)) as str
        from dual
     connect by level <= regexp_count('dog, cat, cat',',') + 1
     )
    ) as str3    
 from dual;

 STR1         STR2           STR3
 ------  ---------------   --------
 apple   prince,princess   cat,dog

Rextester Demo