2

我有一个这样的数据库表:

id   |   check_number        |   amount
1    |   1001]1002]1003      |   200]300]100
2    |   2001]2002           |   500]1000
3    |   3002]3004]3005]3007 |   100]300]600]200

我想将记录分成如下内容:

id   |   check_number    |   amount
1    |   1001            |   200
2    |   1002            |   300
3    |   1003            |   100
.    |     .             |    .
.    |     .             |    .
.    |     .             |    .

如何仅在 Oracle 和 SQL Server 中使用 SQL 来执行此操作?

谢谢,

米洛

4

1 回答 1

2

仅在 Oracle 中,使用 CONNECT BY LEVEL 方法(参见此处),但有几个注意事项:

select rownum, id,
       substr(']'||check_number||']'
              ,instr(']'||check_number||']',']',1,level)+1
              ,instr(']'||check_number||']',']',1,level+1) 
               - instr(']'||check_number||']',']',1,level) - 1) C1VALUE,
       substr(']'||amount||']'
              ,instr(']'||amount||']',']',1,level)+1
              ,instr(']'||amount||']',']',1,level+1) 
               - instr(']'||amount||']',']',1,level) - 1) C2VALUE
    from table
connect by id = prior id and prior dbms_random.value is not null  
      and level <= length(check_number) - length(replace(check_number,']')) + 1


ROWNUM ID  C1VALUE C2VALUE

1      1   1001    200
2      1   1002    300
3      1   1003    100
4      2   2001    500
5      2   2002    1000
6      3   3002    100
7      3   3004    300
8      3   3005    600
9      3   3007    200

本质上,我们使用 oracle 的分层函数爆破查询,然后只获取 check_number 和 amount 列中每个“列”数据中的数据的子字符串。

主要警告:要转换的数据在两列中必须具有相同数量的“数据元素”,因为我们使用第一列来“计算”要转换的项目数。

我已经在 11gR2 上对此进行了测试。YMMV 也取决于 DMBS 版本。请注意需要使用“PRIOR”运算符,它可以防止 oracle 进入无限循环连接。

于 2012-05-10T15:59:25.603 回答