oracle 19Cから組み込まれています こちらをご覧ください
18C以前からグループ内でお試しはこちら
それ以外の場合は、正規表現を使用してください
問題を解決する方法は次のとおりです。
select
regexp_replace(
'2,2,2.1,3,3,3,3,4,4'
,'([^,]+)(,\1)*(,|$)', '\1\3')
from dual
戻り値
2,2.1,3,4
以下の回答:
select col1,
regexp_replace(
listagg(
col2 , ',') within group (order by col2) -- sorted
,'([^,]+)(,\1)*(,|$)', '\1\3') )
from tableX
where rn = 1
group by col1;
注:上記はほとんどの場合に機能します-リストはソートする必要があります。データによっては、末尾と先頭のスペースをすべてトリミングする必要がある場合があります。
グループ内に 20 を超えるアイテムが多数ある場合、または文字列サイズが大きい場合、「文字列連結の結果が長すぎます」というオラクルの文字列サイズ制限に遭遇する可能性があります。
Oracle 12cR2 から、このエラーを抑制することができます。こちらを参照してください。または、各グループのメンバーに最大数を設定します。これは、最初のメンバーのみをリストしても問題ない場合にのみ機能します。非常に長い変数文字列がある場合、これは機能しない可能性があります。実験する必要があります。
select col1,
case
when count(col2) < 100 then
regexp_replace(
listagg(col2, ',') within group (order by col2)
,'([^,]+)(,\1)*(,|$)', '\1\3')
else
'Too many entries to list...'
end
from sometable
where rn = 1
group by col1;
Oracle文字列サイズの制限をうまく回避するための別の解決策(それほど単純ではない)-文字列サイズは4000に制限されています。user3465996によるこの投稿のおかげで
select col1 ,
dbms_xmlgen.convert( -- HTML decode
dbms_lob.substr( -- limit size to 4000 chars
ltrim( -- remove leading commas
REGEXP_REPLACE(REPLACE(
REPLACE(
XMLAGG(
XMLELEMENT("A",col2 )
ORDER BY col2).getClobVal(),
'<A>',','),
'</A>',''),'([^,]+)(,\1)*(,|$)', '\1\3'),
','), -- remove leading XML commas ltrim
4000,1) -- limit to 4000 string size
, 1) -- HTML.decode
as col2
from sometable
where rn = 1
group by col1;
V1 - いくつかのテスト ケース - 参考までに
regexp_replace('2,2,2.1,3,3,4,4','([^,]+)(,\1)+', '\1')
-> 2.1,3,4 Fail
regexp_replace('2 ,2 ,2.1,3 ,3 ,4 ,4 ','([^,]+)(,\1)+', '\1')
-> 2 ,2.1,3,4 Success - fixed length items
V2 - アイテム内に含まれるアイテム。2,21
regexp_replace('2.1,1','([^,]+)(,\1)+', '\1')
-> 2.1 Fail
regexp_replace('2 ,2 ,2.1,1 ,3 ,4 ,4 ','(^|,)(.+)(,\2)+', '\1\2')
-> 2 ,2.1,1 ,3 ,4 -- success - NEW regex
regexp_replace('a,b,b,b,b,c','(^|,)(.+)(,\2)+', '\1\2')
-> a,b,b,c fail!
v3 - 正規表現、Igor に感謝します! すべての場合に機能します。
select
regexp_replace('2,2,2.1,3,3,4,4','([^,]+)(,\1)*(,|$)', '\1\3') ,
---> 2,2.1,3,4 works
regexp_replace('2.1,1','([^,]+)(,\1)*(,|$)', '\1\3'),
--> 2.1,1 works
regexp_replace('a,b,b,b,b,c','([^,]+)(,\1)*(,|$)', '\1\3')
---> a,b,c works
from dual