【问题标题】:How can I eliminate duplicate data in column如何消除列中的重复数据
【发布时间】:2019-04-21 23:28:51
【问题描述】:

我想消除重复并显示一次

例如

SELECT 'apple, apple, orange'
FROM dual;

我想展示

apple, orange

作为另一个例子。

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

我只想展示

apple

这段代码显示

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

【问题讨论】:

  • 为什么标题中有日期?
  • @user7294900 抱歉,这意味着重复数据
  • 你可以编辑你的问题标题
  • @JuanCarlosOropeza。谢谢!!!我做到了!!!

标签: sql regex oracle oracle11g


【解决方案1】:

这样的事情会消除重复:

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

输出

如您所见,您得到一个 NULL,因为额外的逗号 ,

【讨论】:

    【解决方案2】:

    Oracle forum 中有几个选项:

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

    只需将数字替换为'apple, apple, orange'

    【讨论】:

    【解决方案3】:

    trimdistinctregexp 函数一起使用对于获得所需的结果非常重要

    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

    【讨论】:

      猜你喜欢
      • 2019-04-22
      • 2016-06-25
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 2015-02-04
      • 2017-01-05
      • 2019-07-28
      • 2014-01-22
      相关资源
      最近更新 更多