27,579
社区成员
发帖
与我相关
我的任务
分享
--先创建一临时表保存交易值与交易顺序
declare @tmp (id int identity(1,1),
jyz numeric(18,2),--交易值
jcz numeric(18,2) default 0 --结存值
)
--插入交易值
insert into @tmp (jyz) select 50
union select 90
union select 300
union select 80
--计算期初为0的结存值
update a
set jcz=(select sum(jyz) from @tmp where id<=a.id) --计算前面交易值的和
from @tmp a
--将@tmp 插入带期初数的表,将@tmp中结存值加上期初数即为需要的结存值
/*
交易日期 交易值 结存值
2008-01-01 0 100
2008-01-02 50 150
2008-01-03 90 240
2008-01-04 300 540
2008-01-05 80 620
*/
-->生成测试数据
declare @tb table([交易日期] Datetime,[交易值] int,[结存值] int)
Insert @tb
select '2008-01-01',N'0',100 union all
select '2008-01-02',N'50',150 union all
select '2008-01-03',N'90',240 union all
select '2008-01-04',N'300',540 union all
select '2008-01-05',N'80',620
Select *,
(select [结存值] from @tb where [交易日期] = (select min([交易日期]) from @tb) ) +
(select sum([交易值]) from @tb where [交易日期] <= t.[交易日期]) as [新的结存值]
from @tb t
/*
(5 row(s) affected)
交易日期 交易值 结存值 新的结存值
----------------------- ----------- ----------- -----------
2008-01-01 00:00:00.000 0 100 100
2008-01-02 00:00:00.000 50 150 150
2008-01-03 00:00:00.000 90 240 240
2008-01-04 00:00:00.000 300 540 540
2008-01-05 00:00:00.000 80 620 620
(5 row(s) affected)
*/
--> 测试数据: #T
if object_id('tempdb.dbo.#T') is not null drop table #T
create table #T (id int,col2 int)
insert into #T
select 1,50 union all
select 2,90 union all
select 3,300 union all
select 4,80
select id,col2,(select sum(col2) from #t where id<=a.id) as col3 from #T as a
/*
-----------------
1 50 50
2 90 140
3 300 440
4 80 520
*/