CREATE TABLE #penaltytest
(
Earnings NUMERIC(7,2),
Penalties NUMERIC(7,2),
AttDate DATE
)
INSERT INTO #penaltytest VALUES (1000,500, '01 Jan 2000')
INSERT INTO #penaltytest VALUES (0,500, '02 Jan 2000')
INSERT INTO #penaltytest VALUES (0,100, '03 Jan 2000')
INSERT INTO #penaltytest VALUES (0,100, '04 Jan 2000')
INSERT INTO #penaltytest VALUES (500,100, '05 Jan 2000')
INSERT INTO #penaltytest VALUES (400,500, '06 Jan 2000')
;with cte as(
select
AttDate,
Earnings,
Penalties,
Earnings - Penalties as subTotal,
(select
isnull(sum(Earnings - Penalties),0)
from
#penaltytest previousRow
where
previousRow.AttDate < currentRow.AttDate
) as cumulative
from
#penaltytest currentRow
)
select
t.AttDate
,t.Earnings
,t.Penalties
,cte.subTotal
,cte.cumulative
,case when cte.cumulative - (t.Earnings - t.Penalties) >= 0 then 'Yes' else 'No' end as Penalty
from #penaltytest t
join cte
on cte.AttDate = t.AttDate
drop table #penaltytest
Results:
AttDate Earnings Penalties subTotal cumulative Penalty
2000-01-01 1000.00 500.00 500.00 0.00 No
2000-01-02 0.00 500.00 -500.00 500.00 Yes
2000-01-03 0.00 100.00 -100.00 0.00 Yes
2000-01-04 0.00 100.00 -100.00 -100.00 Yes
2000-01-05 500.00 100.00 400.00 -200.00 No
2000-01-06 400.00 500.00 -100.00 200.00 Yes