zoukankan      html  css  js  c++  java
  • 不用循环游标,一句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

  • 相关阅读:
    【Other】申请免费的SSL证书及部署Https协议
    【MySql】mysql-5.7.20-winx64安装配置
    【CSharp】C#程序使用.NET Reactor进行混淆加壳
    【Linux】Ubuntu安装Python3
    【Linux】Ubuntu安装Googlepinyin中文输入法
    【Linux】Ubuntu修改默认源
    【C/S】FIPS安全验证问题
    【Android】apk文件反编译
    笔记之《用python写网络爬虫》
    memcache (持续了解ing...)
  • 原文地址:https://www.cnblogs.com/hhlotus/p/12201674.html
Copyright © 2011-2022 走看看