我不認爲你可以用regexp_replace
做,如果重複的值不相鄰。一種方法是將值分開,消除重複項,然後將它們重新組合。
標記分隔字符串的常用方法是regexp_substr
和connect by
子句。使用綁定變量與您的字符串使代碼更清楚一點:
var value varchar2(100);
exec :value := 'Ian,Beatty,Larry,Neesha,Beatty,Neesha,Ian,Neesha';
select regexp_substr(:value, '[^,]+', 1, level) as value
from dual
connect by regexp_substr(:value, '[^,]+', 1, level) is not null;
VALUE
------------------------------
Ian
Beatty
Larry
Neesha
Beatty
Neesha
Ian
Neesha
您可以使用它作爲一個子查詢(或CTE),從中獲得不同的值,然後重新組裝與listagg
:
select listagg(value, ',') within group (order by value) as value
from (
select distinct value from (
select regexp_substr(:value, '[^,]+', 1, level) as value
from dual
connect by regexp_substr(:value, '[^,]+', 1, level) is not null
)
);
VALUE
------------------------------
Beatty,Ian,Larry,Neesha
這是一個有點如果你正在尋找在表中的多個行作爲混淆連接,通過語法,但你可以使用非determinisitic參考,以避免循環更加複雜:
with t42 (id, value) as (
select 1, 'Ian,Beatty,Larry,Neesha,Beatty,Neesha,Ian,Neesha' from dual
union all select 2, 'Mary,Joe,Mary,Frank,Joe' from dual
)
select id, listagg(value, ',') within group (order by value) as value
from (
select distinct id, value from (
select id, regexp_substr(value, '[^,]+', 1, level) as value
from t42
connect by regexp_substr(value, '[^,]+', 1, level) is not null
and id = prior id
and prior dbms_random.value is not null
)
)
group by id;
ID VALUE
---------- ------------------------------
1 Beatty,Ian,Larry,Neesha
2 Frank,Joe,Mary
當然,如果您正確存儲關係數據,則這不是必需的;在列中使用分隔字符串不是一個好主意。
使用合適的聯結表 - 甚至是嵌套表 - 而不是逗號分隔列表的好原因是什麼。祝你好運。 –
這看起來是[這個]的愚蠢(http://stackoverflow.com/questions/26672269/how-to-remove-duplicates-from-comma-separated-list-by-regex-in-oracle-regexp-代表 – Dave
該模式是不同的,不適用於我的數據。僧侶仍然存在。 – Cindy