例子:
序号 日期 余额
1 20120101
2 20120102
3 20120103 10
4 20120104
5 20120105
6 20120106 20
7 20120107
8 20120108
9 20120109 30
10 20120110
11 20120111
某账号1月3号余额为10元,6号为20元,9号为30元。现需要对余额列为空的数据进行追加,结果为:1号、2号为10元,4号、5号为10元,7号、8号为20元,10号、11号为30元。
请问有什么好办法呢?
select 序号,日期,
(select top 1 余额 from tb where 日期 >= t.日期 order by 日期) 余额
from tb t
create table som
(序号 int, 日期 varchar(12), 余额 int)
insert into som
select 1, '20120101', null union all
select 2, '20120102', null union all
select 3, '20120103', 10 union all
select 4, '20120104', null union all
select 5, '20120105', null union all
select 6, '20120106', 20 union all
select 7, '20120107', null union all
select 8, '20120108', null union all
select 9, '20120109', 30 union all
select 10, '20120110', null union all
select 11, '20120111', null
select * from som
序号 日期 余额
----------- ------------ -----------
1 20120101 NULL
2 20120102 NULL
3 20120103 10
4 20120104 NULL
5 20120105 NULL
6 20120106 20
7 20120107 NULL
8 20120108 NULL
9 20120109 30
10 20120110 NULL
11 20120111 null
update a
set a.余额=
isnull((select b.余额 from som b
where b.余额 is not null and b.序号=
(select max(序号) from som c
where c.余额 is not null and c.序号<a.序号)
),
(select top 1 余额 from som where 余额 is not null))
from som a
where a.余额 is null
select * from som
序号 日期 余额
----------- ------------ -----------
1 20120101 10
2 20120102 10
3 20120103 10
4 20120104 10
5 20120105 10
6 20120106 20
7 20120107 20
8 20120108 20
9 20120109 30
10 20120110 30
11 20120111 30
(11 row(s) affected)