發現一段經典SQL,不用迴圈游標,一句update代碼實現滾動計算結存。為方便理解,結合實例測試之 --1,源數據#t1,jcshl初值為每個sid的當前庫存數量,要實現的效果:每個sid的後一結存數量為前一jcshl結存數量-chkshl出庫數量 SELECT * FROM #t1 ORDER B ...
發現一段經典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