像這樣(假設有在輸入表中沒有重複行 - 如果存在,則溶液需要修改一個位)。
在我建立用於測試的TEST_TABLE(它不是解決方案的一部分),並且我建立另一個因式分解子查詢中WITH子句的溶液。這適用於Oracle 11及更高版本。對於早期版本的Oracle,定義爲prep
子查詢需要被移動,而不是最終的查詢中的子查詢。
with
test_table (id, identifiers) as (
select '1', '|1|2|' from dual union all
select '1', '|2|1|' from dual union all
select '2', '|3|A|1|B|' from dual union all
select '2', '|B|1|3|A|' from dual union all
select '3', '|1|3|2|' from dual union all
select '3', '|1|5|' from dual union all
select '3', '|2|1|3|' from dual union all
select '4', '|AA|BB|1|3A|' from dual union all
select '4', '|1|3A|AA|BB|' from dual
),
prep (id, identifiers, token) as (
select id, identifiers, regexp_substr(identifiers, '[^|]+', 1, level)
from test_table
connect by level <= regexp_count(identifiers, '\|') - 1
and prior identifiers = identifiers
and prior sys_guid() is not null
)
select distinct id,
'|' || listagg(token, '|') within group (order by token) || '|'
as identifiers
from prep
group by id, identifiers
order by id, identifiers -- ORDER BY is optional
;
輸出:
ID IDENTIFIERS
--- --------------------
1 |1|2|
2 |1|3|A|B|
3 |1|2|3|
3 |1|5|
4 |1|3A|AA|BB|
5 rows selected.
你關心,如果該查詢不匹配任何原始行的順序返回標識?例如按字母順序排列(數字在哪裏都可能)? – mathguy
不可以按任何順序退貨! – mlin
而且,單行中的標識符之間是否可以有重複?如果是這樣,你是否需要重複重複正確的次數,或者你可以鞏固它們? – mathguy