子代码 交易类型 入库数量 输入时间
TAHR6307 初始化入库 1942 2011-4-19 0:00
TAHR6307 出库车间 -2262 2011-4-21 14:45
TAHR6307 移库外不良 -20 2011-4-21 14:52
TAHR6307 入库 12010 2011-4-21 16:26
TAHR6307 出库车间 -2502 2011-4-22 15:43
TAHR6307 出库车间 -848 2011-5-6 14:23
TAHR6307 出库车间退货 1 2011-5-9 13:15
TAHR6307 移库外不良 -6 2011-5-9 13:45
TAHR6307 出库车间 -8095 2011-5-11 11:03
TAHR6307 出库领用 -100 2011-5-17 15:52
TAHR6307 入库 14360 2011-6-1 14:29
TAHR6307 出库车间 -2079 2011-6-1 14:30
TAHR6307 出库车间 -8483 2011-6-1 14:34
TAHR6307 出库车间退货 45 2011-6-2 10:56
TAHR6307 入库 -165 2011-6-2 14:18
TAHR6307 入库 14270 2011-6-8 11:14
根据这个 交易表 如何得出
每个月的 期初和期末库存子代码 期初数量  期末数量 月份

解决方案 »

  1.   

    create table tb(子代码 varchar(10),交易类型 nvarchar(10),入库数量 int,输入时间 datetime)
    insert into tb select 'TAHR6307','初始化入库',1942,'2011-4-19 0:00'
    insert into tb select 'TAHR6307','出库车间',-2262,'2011-4-21 14:45'
    insert into tb select 'TAHR6307','移库外不良',-20,'2011-4-21 14:52'
    insert into tb select 'TAHR6307','入库',12010,'2011-4-21 16:26'
    insert into tb select 'TAHR6307','出库车间',-2502,'2011-4-22 15:43'
    insert into tb select 'TAHR6307','出库车间',-848,'2011-5-6 14:23'
    insert into tb select 'TAHR6307','出库车间退货',1,'2011-5-9 13:15'
    insert into tb select 'TAHR6307','移库外不良',-6,'2011-5-9 13:45'
    insert into tb select 'TAHR6307','出库车间',-8095,'2011-5-11 11:03'
    insert into tb select 'TAHR6307','出库领用',-100,'2011-5-17 15:52'
    insert into tb select 'TAHR6307','入库',14360,'2011-6-1 14:29'
    insert into tb select 'TAHR6307','出库车间',-2079,'2011-6-1 14:30'
    insert into tb select 'TAHR6307','出库车间',-8483,' 2011-6-1 14:34'
    insert into tb select 'TAHR6307','出库车间退货',45,'2011-6-2 10:56'
    insert into tb select 'TAHR6307','入库',-165,'2011-6-2 14:18'
    insert into tb select 'TAHR6307','入库',14270,'2011-6-8 11:14'
    go
    ;with c1 as(
    select 子代码 dm,sum(入库数量)sl,convert(varchar(7),输入时间,120)dt from tb 
    group by 子代码,convert(varchar(7),输入时间,120)
    )
    select dm 子代码,(select isnull(sum(sl),0) from c1 where dt<a.dt and dm=a.dm) 期初数量,
    (select sum(sl) from c1 where dt<=a.dt and dm=a.dm)期末数量,dt 月份 from c1 a
    go
    drop table tb
    /*
    子代码        期初数量        期末数量        月份
    ---------- ----------- ----------- -------
    TAHR6307   0           9168        2011-04
    TAHR6307   9168        120         2011-05
    TAHR6307   120         18068       2011-06(3 行受影响)*/