declare @a table(id int,dt varchar(8),qy int)
insert into @a
select 1,'20050505',100
union all select 2,'20050506',-10
union all select 3,'20050506',20select a.id,a.dt,起初数量=isnull((select sum(qy) from @a where id<a.id),0),变动数量=a.qy,后数量=(select sum(qy) from @a where id<=a.id)
from @a a
/*
id dt 起初数量 变动数量 后数量
---------------------------------------------
1 20050505 0 100 100
2 20050506 100 -10 90
3 20050506 90 20 110*/
insert into @a
select 1,'20050505',100
union all select 2,'20050506',-10
union all select 3,'20050506',20select a.id,a.dt,起初数量=isnull((select sum(qy) from @a where id<a.id),0),变动数量=a.qy,后数量=(select sum(qy) from @a where id<=a.id)
from @a a
/*
id dt 起初数量 变动数量 后数量
---------------------------------------------
1 20050505 0 100 100
2 20050506 100 -10 90
3 20050506 90 20 110*/
case when (select sum(t3.变动数量) from b t3 where t3.id<t1.id) is null then 0 else
(select sum(t3.变动数量) from b t3 where t3.id<t1.id) end 期初数量,
t1.变动数量,
(select sum(t3.变动数量) from b t3 where t3.id<=t1.id) 后数量
from b t1