if object_id('test') is not null
drop table test
go
create table test(id int identity,name char(1),i int,o int)
insert into test select 'a',10,null
union all select 'a',null,1
union all select 'a',20,null
union all select 'a',null,25
union all select 'b',5,null
union all select 'b',null,2
select name as 货物名称 ,isnull(i,' ') as 进货量 ,isnull(o,' ') as 出货量 ,库存量=(select sum(isnull(i,0))-sum(isnull(o,0)) from test where id<=t.id and name=t.name) from test t
货物名称 进货量 出货量 库存量
---- ----------- ----------- -----------
a 10 0 10
a 0 1 9
a 20 0 29
a 0 25 4
b 5 0 5
b 0 2 3