使用查询将“ 4030240201”转换为“ 40/3/02/40/201”。
我尝试使用查询将“ 4030240201”转换为“ 40/3/02/40/201”,但未能成功。我要从表中选择位置和数字。
这可以通过递归查询完成吗?怎么样?
With Recursive s As (
select fd.ilevel_pos, fd.ilevel_digits, substr(trim('4030240201'), ilevel_pos::Integer, ilevel_digits::Integer) || '/' as test
from index_detail fd
join index_format lf on fd.formatid = lf.format_id and lf.activeFlag = 1
Where ilevel_pos <= length(Trim('4030240201'))
And ilevel_pos = 1
Union All
select fd.ilevel_pos, fd.ilevel_digits, substr(trim('4030240201'), fd.ilevel_pos::Integer, fd.ilevel_digits::Integer) || '/' as test
from index_detail fd
join index_format lf on fd.formatid = lf.format_id and lf.activeFlag = 1
join S ON (s.ilevel_pos = fd.ilevel_pos)
Where fd.ilevel_pos <= length(Trim('4030240201'))
)
Select test
From s;
Contents of the table index_detail
╔═════════════╦═══════════════╗
║ ilevel_pos ║ ilevel_digits ║
╠═════════════╬═══════════════╣
║ 1 ║ 2 ║
║ 2 ║ 1 ║
║ 3 ║ 2 ║
║ 5 ║ 2 ║
║ 7 ║ 1 ║
║ 8 ║ 3 ║
╚═════════════╩═══════════════╝
我预期为“ 40/3/02/40/201”,但实际输出为“ 40 /”
答案 0 :(得分:-1)
如果我正确理解了您的问题,为什么不只使用子字符串中的位置呢?
with list as ( select '40231' as test, 2 as pos, 3 as leng)
select substring(test, pos, leng) from list
编辑:
with list as ( select '40302402' as test, 1 as pos1, 2 as leng1,3 as pos2, 3 as leng2)
select substring(test, pos1, leng1)+'/' + substring(test, pos2, leng2)+'/' from list
with testing as ( select '40302402' as test, 1 as pos1, 2 as leng1,3 as pos2, 3 as leng2)
select substring(test, pos1, leng1)+'/' + substring(test, pos2, leng2)+'/' from testing
对于postgres,必须更改concat运算符
with testing as ( select '40302402' as test, 1 as pos1, 2 as leng1,3 as pos2, 3 as leng2)
select substring(test, pos1, leng1) || '/' || substring(test, pos2, leng2) ||'/' from testing
答案 1 :(得分:-1)
尝试声明一个包含“ 40302402”值作为输入值的变量
然后尝试选择continue substr的
然后将每个项目合并为一行。
SET input_value := '40302402';
(可能需要解决)
SELECT (
SELECT concat(T.Var1, '/', T.Var2, '/', T.Var3, '/', T.Var4)
FROM (
SELECT
SUBSTRING(input_value, 1, 2) AS Var1,
SUBSTRING(input_value, 3, 3) as Var2,
SUBSTRING(input_value, 5, 1) as Var3,
SUBSTRING(input_value, 6, 2) as Var4
) AS T
) as FormatedValue;
使用变量未经测试。
硬编码版本(如下所示)可以100%工作
SELECT (
SELECT concat(T.Var1, '/', T.Var2, '/', T.Var3, '/', T.Var4)
FROM (
SELECT
SUBSTRING('40302402', 1, 2) AS Var1,
SUBSTRING('40302402', 3, 3) as Var2,
SUBSTRING('40302402', 5, 1) as Var3,
SUBSTRING('40302402', 6, 2) as Var4
) AS T
) as FormatedValue;
问候 院长。
参考: