SQL:如何将组合行分成单独的行

标签 sql sql-server oracle stored-procedures tokenize

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

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/

相关文章:

sql - SELECT 语句返回 ORA-00933 : SQL command not properly ended

c# - 是否可以在sql语句中定义表?

C# 更新 SQL Server 表

sql - 至今年/月/日

c# - Linq/Entity框架中如何获取待创建的ID

sql - 空运算符上的ALL运算符VS Any

sql - SQL 中的分页 - 性能问题

sql - Teradata CASE 和 HAVING COUNT

sql-server - 为什么 xp_cmdshell 在 SQL Server 2012 中不起作用?

java - 与用户相关的线程的响应能力