使用last not null 1填充空值=>大量的列

时间:2015-05-11 14:45:54

标签: sql oracle lag

我想将SOURCE_TABLE中的行复制到TARGET_TABLE,同时填充空值,最后一个空值为空。

我有什么:

SOURCE_TABLE :
       A |    B |    C | PARENT | SEQ_NUMBER
       1 |    2 | NULL |      1 |          1
    NULL | NULL |    1 |      1 |          2
    NULL |    3 |    2 |      1 |          3

DEST_TABLE is empty

我想要的是什么:

DEST_TABLE :
       A |    B |    C | PARENT | SEQ_NUMBER
       1 |    2 | NULL |      1 |          1
       1 |    2 |    1 |      1 |          2
       1 |    3 |    2 |      1 |          3

为了实现这一点,我动态生成以下SQL:

insert into TARGET_TABLE (A, B, C)  
select  coalesce(A, lag(A ignore nulls) over (partition by parent order by seq_number)) as A,  
        coalesce(B, lag(B ignore nulls) over (partition by parent order by seq_number)) as B,  
        coalesce(C, lag(C ignore nulls) over (partition by parent order by seq_number)) as C,  
from SOURCE_TABLE; 

如果SOURCE和TARGET表的列数很少,那么一切正常。在我的情况下,他们有400多列(是的,这是坏的,但它是遗留的,无法更改),我得到以下错误:

  

ORA-01467:排序键太长

  • 首先,我真的不明白这个错误。这是因为我使用过多的滞后函数来使用自己"顺序由" /"分区由" ?通过合并(A,A)替换合并(A,滞后(A ....)),错误消失。
  • 然后,是否有解决方法或其他方法来实现相同的结果?

THX

1 个答案:

答案 0 :(得分:0)

使用pl / sql匿名块执行此操作:

declare
   x tgt_table%rowtype; --keep values from last row
begin
   for r in (select * from src_table order by seq_number) loop
       x.a := nvl(r.a, x.a);
       ...
       x.z := nvl(r.z, x.z);
       insert into tgt_table
       values x;
   end loop;
end;