发现一段经典sql,不用循环游标,一句update代码实现滚动计算结存。为方便理解,结合实例测试之
--1,源数据#t1,jcshl初值为每个sid的当前库存数量,要实现的效果:每个sid的后一结存数量为前一jcshl结存数量-chkshl出库数量 select * from #t1 order by sn
sn plh sid chkshl jcshl
1 s0002 20.0000 980.0000
2 s0003 10.0000 1010.0000
3 s0003 10.0000 1010.0000
4 s0003 10.0000 1010.0000
5 s0002 10.0000 980.0000
6 s0002 1.0000 980.0000
7 s0004 20.0000 720.0000
8 s0005 10.0000 530.0000
9 s0005 10.0000 530.0000
10 s0005 10.0000 530.0000
11 s0004 10.0000 720.0000
12 s0004 1.0000 720.0000
--2,按sid排序#t2,数据顺序决定分组及计算顺序 select * into #t2 from #t1 order by sid,sn
sn plh sid chkshl jcshl
1 s0002 20.0000 980.0000
5 s0002 10.0000 980.0000
6 s0002 1.0000 980.0000
2 s0003 10.0000 1010.0000
3 s0003 10.0000 1010.0000
4 s0003 10.0000 1010.0000
7 s0004 20.0000 720.0000
11 s0004 10.0000 720.0000
12 s0004 1.0000 720.0000
8 s0005 10.0000 530.0000
9 s0005 10.0000 530.0000
10 s0005 10.0000 530.0000
--3,滚动更新jcshl结存数量,同时填入新的plh排列号 declare @plh char(11),@jcshl decimal(18,4),@sid char(11) update #t2 set @jcshl=jcshl=case when sid=@sid then @jcshl-chkshl else jcshl-chkshl end, @plh=plh=str(isnull(@plh,0))+1, @sid=sid=sid select * from #t2
sn plh sid chkshl jcshl
1 1 s0002 20.0000 960.0000
5 2 s0002 10.0000 950.0000
6 3 s0002 1.0000 949.0000
2 4 s0003 10.0000 1000.0000
3 5 s0003 10.0000 990.0000
4 6 s0003 10.0000 980.0000
7 7 s0004 20.0000 700.0000
11 8 s0004 10.0000 690.0000
12 9 s0004 1.0000 689.0000
8 10 s0005 10.0000 520.0000
9 11 s0005 10.0000 510.0000
10 12 s0005 10.0000 500.0000