update tb set
上期余额 =
isnull((select sum(现金1) from tb where 日期 < t.日期),0) +
isnull((select sum(现金2) from tb where 日期 < t.日期),0) ,
本期余额 =
isnull((select sum(现金1) from tb where 日期 <= t.日期),0) +
isnull((select sum(现金2) from tb where 日期 <= t.日期),0)
from tb t
这个问题第8个回答:
SQL code
create table tb (日期 datetime,上期余额 int,现金1 int,现金2 int,本期余额 int)
insert into tb values('2008-9-25 00:00:00' ,0,12,12,24)
insert into tb values('2008-9-25 00:00:01' ,24,3,2,29 )
insert into tb values('2008-9-25 00:01:00' ,29,4,-2,31)
insert into tb values('2008-9-25 01:00:00' ,31,2,2,35)
go
--原始数据
select * from tb
/*
日期 上期余额 现金1 现金2 本期余额
------------------------------------------------------ ----------- ----------- ----------- -----------
2008-09-25 00:00:00.000 0 12 12 24
2008-09-25 00:00:01.000 24 3 2 29
2008-09-25 00:01:00.000 29 4 -2 31
2008-09-25 01:00:00.000 31 2 2 35
(所影响的行数为 4 行)
*/
--例如:将2)修改为: 2)2008-9-25 00:00:01 ,24,4,2,30
update tb set 现金1 = 4 where 日期 = '2008-9-25 00:00:01'
--修改其他数据
update tb
set 上期余额 =
isnull((select sum(现金1) from tb where 日期 < t.日期),0) +
isnull((select sum(现金2) from tb where 日期 < t.日期),0) ,
本期余额 =
isnull((select sum(现金1) f