Es ist auf jeden Fall ziemlich viele Möglichkeiten, dies zu tun. Abhängig von der Größe Ihres Datensatzes und anderen Faktoren finden Sie Vor- und Nachteile.
Hier ist meine Empfehlung ...
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).
ich die zweite Methode am besten gefällt, weil es nur berechnen, wenn es einen Datensatz für den vorangegangenen Monat existiert.
(im folgenden auf die obige Skript fügen Sie den Unterschied zu sehen)
--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
Es ist alles eine Frage der genau das, was Sie wünschen. Verwenden Sie den Datensatz, der den aktuellen Datensatz (unabhängig vom Datum) direkt verarbeitet, oder verwenden Sie NUR den Datensatz, der sich einen Monat vor dem aktuellen Datensatz befindet.
Sorry über das Format ... Stackoverflow.com Antwort Editor und ich nicht gut zusammen spielen.
: D
hatte bereits eine equlivant Funktion Datum, aber diese Antwort hat mich in die richtige Richtung, danke! –