向行添加/赋值,前一行为null

时间:2011-06-30 11:09:14

标签: sql sql-server

您好我想在SQL Server 2005

中为行添加/赋值为空前一行值

示例:

Col1  Col2 
1      45
NULL   30
2      20
3      40
NULL   30
NULL   20
4      40

输出必须像这样

Col1  Col2 
1      45
1      30
2      20
3      40
3      30
3      20
4      40

3 个答案:

答案 0 :(得分:2)

除非表中有另一列来决定订单,否则无法完成

没有ORDER BY的SQL中有没有保证顺序。因此,我们不知道哪些NULL会从数据库中读取数据的位置或顺序。

需要ORDER BY来保证任何订单,并且数据首先带有NULL,然后填充行。如果没有ORDER BY的SELECT确实按上述预期顺序返回行,那么它只是巧合

答案 1 :(得分:2)

declare @table as table(Col1 int,Col2 int)

insert into @table values(1,45)
insert into @table values(NULL,30)
insert into @table values(2,20)
insert into @table values(3,40)
insert into @table values(NULL,30)
insert into @table values(NULL,20)
insert into @table values(4,40)

select * from @table

while exists(select 1 from @table where Col1 is null)
begin
update t1 set t1.Col1=t2.Col1 from
     (select ROW_NUMBER() over(order by (select 0)) as RowNo,Col1 
            from @table)as t1 cross apply 
     (select top 1 * from (select ROW_NUMBER() over(order by (select 0)) as RowNo,Col1
            from @table)as t 
     where t.RowNo<t1.RowNo order by RowNo desc)t2 where t1.Col1 is null
end

select * from @table

如果您不关心性能,此查询适用于您!

答案 2 :(得分:1)

我假设您有一个名为id的列是主键,或者您的默认订单是由此字段生成的,我假设您的表的名称是t1。

这是一个提供所需结果的查询:

SELECT * FROM T1
WHERE col1 IS NOT NULL
UNION ALL 
SELECT a.id, nested.col1, a.col2 FROM t1 as a 
    CROSS APPLY 
        (SELECT TOP 1 * FROM t1 as b WHERE a.id > b.id and b.col1 IS NOT NULL ORDER BY b.id DESC) nested
WHERE a.col1 IS NULL
ORDER BY id