【问题标题】:How can I eliminate duplicate data in multiple columns query如何消除多列查询中的重复数据
【发布时间】:2019-04-22 00:45:27
【问题描述】:

我刚刚问了关于如何消除列中重复数据的问题

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

【问题讨论】:

  • 你为什么要做这个练习,更重要的是为什么你要把所有这些分隔的字符串存储在单列中?这是一种糟糕的设计实践,应该不惜一切代价避免。毫无疑问,你会从这里的某个人那里得到一个解决方案,但是在生产代码中放置这样一个可怕的结构是不值得的。更好的方法应该是通过遵循规范化规则来修改表结构/模式。

标签: sql regex oracle oracle11g


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-04-21
    • 2016-09-14
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2020-08-09
    • 2023-03-18
    相关资源
    最近更新 更多