Oracle SQL合并具有相同ID但无序标识符的多个行

时间:2016-11-01 19:01:51

标签: oracle

我正在尝试创建一个独特的部件列表,以便在表格中进行分析。该表包含一列零件ID和一列标识符。标识符通过管道在同一条目内分隔,但不幸的是标识符出现故障。我不确定这是否可行,但任何帮助都将不胜感激!

例如(当前ID和标识符都是VARCHAR2)

ID  Identifiers
1   |1|2|
1   |2|1|
2   |3|A|1|B|
2   |B|1|3|A|
3   |1|3|2|
3   |1|5|
3   |2|1|3|
4   |AA|BB|1|3A|
4   |1|3A|AA|BB|

我需要查询返回

ID  Identifiers
1   |1|2|
2   |3|A|1|B|
3   |1|5|
3   |1|3|2|
4   |1|AA|BB|3A|

只要该标识符中的所有内容都相同,标识符的排序顺序无关紧要。例如,| 1 | 5 |或| 5 | 1 |没关系,但我需要看两个条目| 1 | 5 |和| 1 | 3 | 2。我最初的想法是将标识符单独创建为单独的列,然后按字母顺序连接回一列,但我不确定...提前感谢!

1 个答案:

答案 0 :(得分:1)

这样的事情(假设输入表中没有重复的行 - 如果存在,则需要稍微修改一下解决方案。)

在解决方案中,我构建了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.
相关问题