如何在 Oracle 中的每个破折号后分割字符并根据提取的值创建新列?
How to divide characters after every dash in Oracle and create new columns based on extracted values?
这是我的数据示例:
ID
3-1-2
4-50-15
我想要的是:
ID1
ID2
ID3
3
1
2
4
50
15
最好的方法是什么?
使用SUBSTR
和INSTR
(因为它比正则表达式更快):
SELECT SUBSTR(ID, 1, INSTR(ID, '-', 1, 1) - 1) AS ID1,
SUBSTR(
ID,
INSTR(ID, '-', 1, 1) + 1,
INSTR(ID, '-', 1, 2) - INSTR(ID, '-', 1, 1) - 1
) AS ID2,
SUBSTR(ID, INSTR(ID, '-', 1, 2) + 1) AS ID3
FROM table_name;
其中,对于示例数据:
CREATE TABLE table_name (ID) AS
SELECT '3-1-2' FROM DUAL UNION ALL
SELECT '4-50-15' FROM DUAL;
输出:
ID1
ID2
ID3
3
1
2
4
50
15
如果您确实想使用(较慢的)正则表达式,那么:
SELECT REGEXP_SUBSTR(id, '[^-]+', 1, 1) AS id1,
REGEXP_SUBSTR(id, '[^-]+', 1, 2) AS id2,
REGEXP_SUBSTR(id, '[^-]+', 1, 3) AS id3
FROM table_name;
sqlfiddle here
这是我的数据示例:
ID |
---|
3-1-2 |
4-50-15 |
我想要的是:
ID1 | ID2 | ID3 |
---|---|---|
3 | 1 | 2 |
4 | 50 | 15 |
最好的方法是什么?
使用SUBSTR
和INSTR
(因为它比正则表达式更快):
SELECT SUBSTR(ID, 1, INSTR(ID, '-', 1, 1) - 1) AS ID1,
SUBSTR(
ID,
INSTR(ID, '-', 1, 1) + 1,
INSTR(ID, '-', 1, 2) - INSTR(ID, '-', 1, 1) - 1
) AS ID2,
SUBSTR(ID, INSTR(ID, '-', 1, 2) + 1) AS ID3
FROM table_name;
其中,对于示例数据:
CREATE TABLE table_name (ID) AS
SELECT '3-1-2' FROM DUAL UNION ALL
SELECT '4-50-15' FROM DUAL;
输出:
ID1 ID2 ID3 3 1 2 4 50 15
如果您确实想使用(较慢的)正则表达式,那么:
SELECT REGEXP_SUBSTR(id, '[^-]+', 1, 1) AS id1,
REGEXP_SUBSTR(id, '[^-]+', 1, 2) AS id2,
REGEXP_SUBSTR(id, '[^-]+', 1, 3) AS id3
FROM table_name;
sqlfiddle here