declare @t table(Inv char(3),InOutType varchar(3),Iquantity int)
insert into @t values('001','in',300)
insert into @t values('001','out',200)
insert into @t values('002','in',50)
select a.Inv,isnull(a.入帐,0)-isnull(b.出帐,0) 结余
from
(
select Inv,sum(Iquantity) 入帐 from @t where InOutType='in' group by Inv
) a
left join
(
select Inv,sum(Iquantity) 出帐 from @t where InOutType='Out' group by Inv
) b
on a.Inv=b.Inv
/*
Inv
结余
---- -----------
001
100
002
50
(所影响的行数为 2 行)
*/