在值之间填充空行

时间:2013-10-25 15:54:21

标签: sql sql-server tsql

我需要从前一行继续执行值,直到它达到另一个新值。 LAG不起作用,因为它只填充1行,根据订单号,我可能有1到12行。

ColumnA是我的行号,columnB是我需要填充的列,直到它到达下一个非空白。任何帮助都非常感谢,因为我没有想法。

行就像这样

Columna  Columb  ColumnC  ColumnD
12       Yarn    Yellow   Coarse
13               Yellow   Coarse
14       Needles Size G   Steel
15               Size H   Wood
16               Size Y   Wood
17       Hooks   Fish     Steel
18               Whale    Steel
18               Dolphin  Steel
19               Mermaid  Steel

1 个答案:

答案 0 :(得分:0)

给定字段A是不间断的序列..

Table
A        B        C        D
12       Yarn     Yellow   Coarse 
13                Yellow   Coarse 
14       Needles  Size G   Steel 
15                Size H   Wood 
16                Size Y   Wood 
17       Hooks    Fish     Steel 
18                Whale    Steel 
19                Dolphin  Steel 
20                Mermaid  Steel

我的第一次通过

Select 
   T1.A
   COALESCE(T2.A,T1.B) as B,
   T1.C,
   T1.D 

From
    Table as T1
    LEFT JOIN Table as T2 ON T2.A = T1.A -1

新答案

Select 
   T1.A
   Coalesce(
       T1.B,
       (
           Select top 1 B 
           FROM Table 
           WHERE A < T1.A 
            and B IS Not Null
           ORDER BY A DESC
       )
    ) as B,
    T1.C,
    T1.D 
FROM    
    Table as T1