我不确定我是否正确地解释了这个场景,但这是我所做的:
首先,我将创建几个变量来模拟函数的输入,然后编写一个递归公用表表达式 (RCTE) 以使用从这些变量中获得的数据生成报告:
create variable OpenedWith decimal default 5000
;
create variable Factor decimal(2, 1) default 0.1
;
with
t (adjustment) as ( values(100), (200), (300) )
, ordRows (rn, Adjustment ) as
( select row_number() over(), Adjustment from t )
, addRows (rn, Opening, Shift, Adjustment, closing ) as
( select rn, OpenedWith, OpenedWith*Factor , Adjustment
, ( OpenedWith + ( OpenedWith*Factor ) + Adjustment )
from ordRows
where rn = 1
union all
select b.rn, a.Closing, a.Closing * Factor , b.Adjustment
, ( a.Closing + (a.Closing * Factor) + b.Adjustment )
from addRows a
join ordRows b
on a.rn = ( b.rn - 1 )
)
select int(rn) as rn, int(opening) as opening
, int(shift) as shift, adjustment
, int(closing) as closing
from addRows
以下是上述查询的报告:
RN OPENING SHIFT ADJUSTMENT CLOSING
1 5,000 500 100 5,600
2 5,600 560 200 6,360
3 6,360 636 300 7,296
现在修改上面的脚本变量创建和查询到一个用户定义的表函数(UDTF),它对名为 T 的 TABLE 中的数据进行操作:
create function shifted_vals
( OpenedWith decimal( 5 )
, Factor decimal( 3, 2)
)
returns table
( Opening int
, Shift int
, Adjustment int
, Closing int
)
return
with
ordRows (rn, Adjustment ) as
( select row_number() over(), Adjustment from t )
, addRows (rn, Opening, Shift, Adjustment, closing ) as
( select rn, OpenedWith, OpenedWith*Factor , Adjustment
, ( OpenedWith + ( OpenedWith*Factor ) + Adjustment )
from ordRows
where rn = 1
union all
select b.rn, a.Closing, a.Closing * Factor , b.Adjustment
, ( a.Closing + (a.Closing * Factor) + b.Adjustment )
from addRows a
join ordRows b
on a.rn = ( b.rn - 1 )
)
select opening, shift, adjustment, closing
from addRows
order by rn
现在调用 UDTF 并使用注明的开盘值和因子作为参数;即不再依赖于创建的变量,而是通过输入参数获得的值:
select t.*
from table(shifted_vals(5000, 0.1)) as t
; -- results as report, follows:
OPENING SHIFT ADJUSTMENT CLOSING
5,000 500 100 5,600
5,600 560 200 6,360
6,360 636 300 7,296