假设我有field_name
-field_len
对的键值表。
如下:
-----------------------------------
field_name | field_len |
-----------------------------------
FIELD_A | 10 |
-----------------------------------
FIELD_B | 20 |
-----------------------------------
...
-----------------------------------
FIELD_X | 2 |
-----------------------------------
FIELD_Y | 100 |
-----------------------------------
然后我需要每个字段的偏移量在第三列中。 像这样:
-----------------------------------------------------
field_name | field_len | offset |
-----------------------------------------------------
FIELD_A | 10 | 0 |
-----------------------------------------------------
FIELD_B | 20 | 10 |
-----------------------------------------------------
...
-----------------------------------------------------
FIELD_X | 2 | 250 |
-----------------------------------------------------
FIELD_Y | 100 | 252 |
-----------------------------------------------------
with offsets (column_name, length, offset) as
((select column_name, length, CAST(0 AS SMALLINT)
from myschema.sizes a
start with rrn(a) = 1)
union all
(select b.column_name, b.length, offset + o.length
from offsets o, myschema.sizes b
where rrn(b) between 2 and 100))
select * from offsets;
但是,它不断陷入无限循环。
此版本也提供了相同的结果:
with offsets (column_name, length, offset) as
((select column_name, length, CAST(0 AS SMALLINT)
from myschema.sizes a
fetch first row only)
union all
(select b.column_name, b.length, offset + o.length
from offsets o join myschema.sizes b on b.column_name = o.column_name
where o.column_name <>'LAST_FIELD'))
select * from offsets;
我猜想,这与退出条件混为一谈,但无法找到修复它的确切位置。
最好避免任何特定于表的元数据,例如行数。
答案 0 :(得分:2)
您不需要递归CTE。只是一个累加的总和。像这样:
select s.*,
(sum(field_len) over (order by rrn(s)) - field_len) as offset
from myschema.sizes s;
我不确定如何定义顺序。它似乎基于函数rrn()
。