肯定有不少方法可以做到這一點。你會發現利弊取決於你的數據集有多大,以及其他因素。
這裏是我的建議......
Declare @table as table
(
EOMDate DateTime,
DandA float,
Coupon Float,
EarnedIncome Float
)
Insert into @table Values('04/30/2008', 20187.5,17812.5,NULL)
Insert into @table Values('05/31/2008', 24640.63, 22265.63, NULL)
Insert into @table Values('06/30/2008', 2375, 26718.75,NULL)
--If we know that EOMDate will only contain one entry per month, and there's *always* one entry a month...
Update @Table Set
EarnedIncome=DandA-
(Select top 1 DandA
from @table t2
where t2.EOMDate<T1.EOMDate
order by EOMDate Desc)+Coupon
From @table T1
Select * from @table
--If there's a chance that there could be more per month, or we only want the values from the previous month (do nothing if it doesn't exist)
Update @Table Set
EarnedIncome=DAndA-(
Select top 1 DandA
From @table T2
Where DateDiff(month, T1.EOMDate, T2.EOMDate)=-1
Order by EOMDate Desc)+Coupon
From @Table T1
Select * from @table
--Leave the null, it's good for the data (since technically you cannot calculate it without a prior month).
我喜歡第二種方法最好,因爲如果存在對上月的紀錄只會計算。
(以下內容添加到上面的腳本看出差別)
--Add one for August
Insert into @table Values('08/30/2008', 2242, 22138.62,NULL)
Update @Table Set
EarnedIncome=DAndA-(
Select top 1 DandA
From @table T2
Where DateDiff(month, T1.EOMDate, T2.EOMDate)=-1
Order by EOMDate Desc
)+Coupon
From @Table T1
--August is Null because there's no july
Select * from @table
這是你想要什麼做的所有的事。 使用記錄直接進行當前記錄(不管日期),還是隻使用當前記錄前一個月的記錄。
對不起格式... Stackoverflow.com的答案編輯器,我不在一起玩。
:D
已經有了equivavant日期功能,但這個答案讓我指出了正確的方向,謝謝! – 2009-05-21 15:54:08