日期:2014-05-19  浏览次数:20495 次

关于合计问题,大伙请进
查询结构如下:

日期       单号   进货数量  
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

就是把数量逐条累加到 '总库存 '字段,请问语句该怎么写?


------解决方案--------------------
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.进货数量,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
*/
------解决方案--------------------
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

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

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 , 5

select a.DATETIME,a.ID,a.number, (select sum(number) from TABLETEST where a.DATETIME> =DATETIME)
from TABLETEST a

------解决方案--------------------
01-01 1 1 1
01-02 2 2 3
01-03 3 4 7
01-04 4 5 12