查询结构如下:日期   单号 进货数量 
01-01  1    1        
01-02  2    2
01-03  3    4
01-04  4    5
要求实现:日期   单号 进货数量 总库存
01-01  1    1        1 
01-02  2    2        3
01-03  3    4        7
01-04  4    5        12就是把数量逐条累加到'总库存'字段,请问语句该怎么写?

解决方案 »

  1.   

    select 
        a.日期,a.单号,a.进货数量,sum(b.进货数量) as 总库存
    from 
        表 a,表 b 
    where 
        a.日期>b.日期 
    group by 
        a.日期,a.单号,a.进货数量
      

  2.   

    declare @t table(日期 varchar(6),单号 int,进货数量 int)
    insert into @t select '01-01',1,1
    insert into @t select '01-02',2,2
    insert into @t select '01-03',3,4
    insert into @t select '01-04',4,5select 
        a.日期,a.单号,a.进货数量,sum(b.进货数量) as 总库存
    from 
        @t a,@t b 
    where 
        a.日期>=b.日期 
    group by 
        a.日期,a.单号,a.进货数量/*
    日期   单号        进货数量     总库存         
    ------ ----------- ----------- ----------- 
    01-01  1           1           1
    01-02  2           2           3
    01-03  3           4           7
    01-04  4           5           12
    */
      

  3.   

    declare @t table(日期 varchar(6),单号 int,进货数量 int)
    insert into @t select '01-01',1,1
    insert into @t select '01-02',2,2
    insert into @t select '01-03',3,4
    insert into @t select '01-04',4,5
    select  a.日期,a.单号,a.进货数量, (select sum(进货数量) from @t where a.日期>=日期)
    from   @t a
      

  4.   

    select 
        a.日期,a.单号,a.进货数量,sum(b.进货数量) as 总库存
    from 
        @t a,@t b 
    where 
        a.日期>=b.日期 
    group by 
        a.日期,a.单号,a.进货数量
      

  5.   


    CREATE  TABLE TABLETEST
    (
       DATETIME  VARCHAR(6),
      ID   INT,
      number int,) 
    insert into TABLETEST
    select 
    '01-01',  1 ,   1       union all  select 
    '01-02' , 2  ,  2  union all  select 
    '01-03' , 3  ,  4  union all  select 
    '01-04',  4  ,  5select  a.DATETIME,a.ID,a.number, (select sum(number) from TABLETEST where a.DATETIME>=DATETIME)
    from  TABLETEST  a