【发布时间】:2011-05-18 11:59:51
【问题描述】:
对于我正在做的项目,我需要根据 2 个维度(“自 1900 年以来的天数”和收益率)插入一个值(利率)
我目前有以下代码,其中 f 是插值:
declare @rates table (
days int,
yield int,
rate decimal(18,6)
)
insert into @rates (days,yield,rate)
values (1,30,0.1),
(1,90,0.2),
(3,30,0.2),
(null,3,90,0.4)
declare @data table(
id int,
days int,
yield int)
insert into @data(id,date,days,yield) values
(1,2,60)
select r.*
-- calculation below does not work if x or y ends up being the same
-- (because they all cancel each other out)
,finalinterp = ((f11/((x2 - x1)*(y12 - y11)))*(x2 - x)*(y12 - y))
+ ((f21/((x2 - x1)*(y22 - y21)))*(x - x1)*(y22 - y))
+ ((f12/((x2 - x1)*(y12 - y11)))*(x2 - x)*(y - y11))
+ ((f22/((x2 - x1)*(y22 - y21)))*(x - x1)*(y - y21))
from
(
select id,d.days as x,isnull(x1,x2) x1 ,isnull(x2,x1) x2,d.yield as y,
ISNULL(y11,y12) y11,ISNULL(y12,y11) y12,ISNULL(y21,y22) y21,ISNULL(y22,y21) y22,
r11.rate as f11,
r12.rate as f12,
r21.rate as f21,
r22.rate as f22
from @data d
cross apply
(
select MAX(r.days) as x1 from @rates r1
where r.days <= d.days
) xt1
cross apply
(
select MIN(r.days) as x2 from @rates r1
where days >= d.days
) xt2
cross apply
(
select MAX(yield) as y11 from @rates r1
where r1.days = isnull(x1,x2)
and yield <= d.yield
) yt1
cross apply
(
select MIN(yield) as y12 from @rates r1
where r1.days = isnull(x1,x2)
and yield >= d.yield
) yt2
cross apply
(
select MAX(yield) as y21 from @rates r1
where r1.days = isnull(x2,x1)
and yield <= d.yield
) yt3
cross apply
(
select MIN(yield) as y22 from @rates r1
where r1.days = isnull(x2,x1)
and yield >= d.yield
) yt4
left outer join @rates r11 on r11.mdays = isnull(x1,x2) and r11.yield = ISNULL(y11,y12)
left outer join @rates r12 on r12.mdays = isnull(x1,x2) and r12.yield = ISNULL(y12,y11)
left outer join @rates r21 on r21.mdays = isnull(x2,x1) and r21.yield = ISNULL(y21,y22)
left outer join @rates r22 on r22.mdays = isnull(x2,x1) and r22.yield = ISNULL(y22,y21)
) r
目前这适用于正确解释的值,但是如果该值实际存在(例如,如果我设置 data.yield = 90 或 data.days = 1),因此不需要插值,它会在尝试时分崩离析除以零。
有人能弄清楚如何让它在这种情况下工作吗?
还有更有效的方法吗?在现实世界中,同一查询中有其他表的完整混搭,因此越简洁越好
谢谢
【问题讨论】:
-
根据插值的要求,您的查询的整个基础可能存在问题。如果您需要准确地执行此操作,插值收益率或利率需要对持续时间进行线性插值(正如您尝试做的那样),但需要对收益率进行几何插值。
-
这是因为两个“x”(持续时间)点的“y”或屈服点可能不同吗?您知道我尝试过但找不到任何有用的链接吗
-
这是因为收益率是复利,而不是单利。所以半年的收益率是 (1+i)^1/2 -1 而不是 i/2。谷歌计算复利;或精算利息;或贷款或 APR 法规。我自己没有进行这些搜索,但相信他们应该提供相关材料。
-
已与客户确认,对于该特定系统,两个维度的直线都可以。无论如何感谢您的信息
标签: sql sql-server interpolation