有一个数据库表结构如下
  日期    入库数量    入库金额   出库数量   出库金额   库存数量   库存金额
11-01      12              12      34          34          3           5
11-02      3                4      5            6          空          空
11-03       ……         ……      ……       ……         空          空
……
……
就是我知道每天的入库数量,入库金额,出库数量,出库金额,如果当天没有入库或者出库数值为0,但是库存数量只知道第一天的,我怎么把后面每天空着的库存数量,库存金额计算出来然后添加到表中?我知道计算方法,但不会用sql语句写,求教各位了,给个示例代码吧

解决方案 »

  1.   

    --假设累积库存和累积金额是上期的,与本期无关(此处的期为所添加一行所代表的日期,即以日为期)
    create table tb(dt datetime,rksl int,rkje int,cksl int,ckje int,ljkc int,ljje int)
    insert into tb select '2010-11-01',12,12,34,34,3,5
    union all select '2010-11-02',3,4,5,6,null,null
    union all select '2010-11-03',7,8,9,10,null,null
    go
    with cte as(
    select top 1 * from tb
    union all
    select a.dt,a.rksl,a.rkje,a.cksl,a.ckje,a.rksl-a.cksl+b.ljkc as ljkc,a.rkje-a.ckje+b.ljje as ljje
    from tb a,cte b where a.ljkc is null and b.ljkc is not null and datediff(dd,b.dt,a.dt)=1
    )select * from cte
    go
    drop table tb
    /*
    dt                      rksl        rkje        cksl        ckje        ljkc        ljje
    ----------------------- ----------- ----------- ----------- ----------- ----------- -----------
    2010-11-01 00:00:00.000 12          12          34          34          3           5
    2010-11-02 00:00:00.000 3           4           5           6           1           3
    2010-11-03 00:00:00.000 7           8           9           10          -1          1(3 行受影响)
    */
      

  2.   

    重新审视了一下,修改为:
    --假设累积库存和累积金额是上期的,与本期无关(此处的期为所添加一行所代表的日期,即以日为期)
    create table tb(dt datetime,rksl int,rkje int,cksl int,ckje int,ljkc int,ljje int)
    insert into tb select '2010-11-01',12,12,34,34,3,5
    union all select '2010-11-02',3,4,5,6,null,null
    union all select '2010-11-03',7,8,9,10,null,null
    go
    with cte as(
    select top 1 * from tb
    union all
    select a.dt,a.rksl,a.rkje,a.cksl,a.ckje,b.rksl-b.cksl+b.ljkc as ljkc,b.rkje-b.ckje+b.ljje as ljje
    from tb a,cte b where a.ljkc is null and b.ljkc is not null and datediff(dd,b.dt,a.dt)=1
    )select * from cte
    go
    drop table tb
    /*
    dt                      rksl        rkje        cksl        ckje        ljkc        ljje
    ----------------------- ----------- ----------- ----------- ----------- ----------- -----------
    2010-11-01 00:00:00.000 12          12          34          34          3           5
    2010-11-02 00:00:00.000 3           4           5           6           -19         -17
    2010-11-03 00:00:00.000 7           8           9           10          -21         -19(3 行受影响)
    */
      

  3.   

    昨天和今天的关系
    Select a.*,b.* from tb2 a ,tb2 b where cast(a.str1 as datetime)=cast(b.str1 as datetime)-1
    再想怎么计算都可以了吧!