2
對於一個項目我做我需要根據2種尺寸(「自1900年以來天及產量)雙線性插值在SQL
內插的值(利率)目前,我有下面的代碼,其中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),因此不需要進行插值當它試圖用零來除數時,它就會崩潰。
有人可以弄清楚如何使它在這種情況下工作嗎?
還有沒有一個更有效的方法呢?在現實世界中有其他表在同一個查詢的整體混搭所以更簡潔越好
感謝以下
根據插值的要求,可能您的查詢的整個基礎是有問題的。如果您需要準確地做到這一點,插值收益率或利率需要持續時間的線性插值(正如您試圖這樣做),但需要對收益率進行幾何插值。 – 2011-05-16 10:44:49
這是因爲'y'或屈服點可能不是兩個'x'(持續時間)點相同嗎?你知道我嘗試過的任何有用的鏈接,但不能找到任何東西 – Mark 2011-05-16 22:01:20
這是因爲收益率是複利,而不是單純的利息。所以半年的收益率是(1 + i)^ 1/2 -1而不是i/2。 Google計算複合利息;或精算利益;或貸款或APR法規。我自己沒有做過這些搜索,但相信他們應該提出相關材料。 – 2011-05-17 06:10:34