我有一个像这样的数据库表:
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 来执行此操作?
谢谢
米洛
最佳答案
仅在 Oracle 中,使用 CONNECT BY LEVEL 方法(请参阅 here ),但有几个注意事项:
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 进入无限连接循环。
关于SQL:如何将组合行分成单独的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10536146/