MS SQL问题,如何将下行值为0则取上一行的值?

来源:百度知道 编辑:UC知道 时间:2024/09/24 23:46:15
列表如下
列A
0
0
0
0
4
0
0
0
87
0
0

SQL怎么写才会成为
列A
0
0
0
0
4
4
4
4
87
87
87

只有一列没法改,至少要有一个不重复的ID列,然后用游标来改,参考以下示例:
declare @t table (id int,val int)
insert @t
select 1,0 union all
select 2,0 union all
select 3,0 union all
select 4,0 union all
select 5,4 union all
select 6,0 union all
select 7,0 union all
select 8,0 union all
select 9,87 union all
select 10,0 union all
select 11,0

declare @id int,@val int,@preval int
declare cursor_@t cursor for select * from @t
open cursor_@t
fetch next from cursor_@t into @id,@val
set @preval=@val
while @@fetch_status=0
begin
if @val=0
update @t set val=@preval where id=@id
else
set @preval=@val
fetch next from cursor_@t into @id,@val
end

close cursor_@t
deallocate cursor_@t

select * from @t

以上在SQL2000中测试通过。