VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 数据库 > SQL教程 >
  • 不用循环游标,一句update代码实现滚动计算

发现一段经典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


相关教程