我在Oracle SQL表中有一个字符串字段值。是否有任何查询可以将字符串拆分为新行,每行中有一定数量的相等字符,底部有多余的字符?
eg- ABCDEFGHIJ
我想有相同字符数的行,每行4个字符,如下
ABCD
EFGH
IJ
剩下的两个字母应该在底部。是否可以使用Oracle sql查询实现这一点?
您可以根据字符串的长度使用CONNECT BY和LEVEL来使用如下查询。
WITH d AS (SELECT 'ABCDEFGHIJ' AS str FROM DUAL)
SELECT SUBSTR (str, ((LEVEL - 1) * 4) + 1, 4) AS four_letters
FROM d
CONNECT BY LEVEL < (LENGTH (str) / 4) + 1;
如果有多行,可以将OUTER APPLY
与分层查询一起使用:
SELECT s.split_value,
s.position
FROM table_name t
OUTER APPLY (
SELECT LEVEL AS position,
SUBSTR( t.value, 4 * LEVEL - 3, 4 ) AS split_value
FROM DUAL
CONNECT BY LEVEL <= CEIL( LENGTH( t.value ) / 4 )
) s
对于样本数据:
CREATE TABLE table_name ( value ) AS
SELECT 'ABCDEFGHIJ' FROM DUAL UNION ALL
SELECT '123456789012' FROM DUAL;
输出:
SPLIT_VALUE|POSITION:---------|-------:ABCD |1EFGH |2IJ|31234|15678|29012|3
db<gt;小提琴这里
更新
如果我想在一行中有36个
单词字符,我如何修改你的第一个答案?
SELECT s.split_value,
s.position
FROM table_name t
OUTER APPLY (
SELECT LEVEL AS position,
SUBSTR( t.value, 36 * ( LEVEL - 1 ) + 1, 36 ) AS split_value
FROM DUAL
CONNECT BY LEVEL <= CEIL( LENGTH( t.value ) / 36 )
) s
对于样本数据:
CREATE TABLE table_name ( value ) AS
SELECT 'ABCDEFGHIJ' FROM DUAL UNION ALL
SELECT '________10________20________30________40________50________60________70________80' FROM DUAL;
输出:
SPLIT_VALUE|POSITION:------------------------------|-------:ABCDEFGHIJ|1________10 ________ 20 ________ 30 ________ |1__40 ________ 50 ________ 60 ________ 70__|2______80|3
db<gt;小提琴这里