I think this might work for you. First, here is how I defined my test pattern and test data:
declare @stock table (
transId int not null identity(1,1),
[date] date not null,
input decimal(7,2) null,
[output] decimal(7,2) null
);
insert into @stock values
('1/23/2011', 12.22, null),
('1/23/2011', null, 2.22),
('1/24/2011', 16, null),
('1/24/2011', 3.76, null),
('1/24/2011', null, 5.50);
, , . . , AND b.[date] = a.[date].
select
[date],
input = isnull(input,0),
[output] = isnull([output],0),
balance = (isnull(input,0)-isnull([output],0)) +
isnull((
select
sum((isnull(input,0)-isnull([output],0)))
from @stock b
where b.transId < a.transId
and b.[date] = a.[date]
),0)
from @stock a
order by transId;
:
date input output balance
2011-01-23 12.22 0.00 12.22
2011-01-23 0.00 2.22 10.00
2011-01-24 16.00 0.00 16.00
2011-01-24 3.76 0.00 19.76
2011-01-24 0.00 5.50 14.26
, , . , , , .