读书人

关于合计有关问题大伙请进

发布时间: 2012-01-08 22:48:50 作者: rapoo

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

日期 单号 进货数量
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-01111
01-02223
01-03347
01-044512

读书人网 >SQL Server

热点推荐