1

我当前的表格输出是

        ---------------------------------------------------
        |    id               col1            col2        |
        ---------------------------------------------------
        |    1           |    test1      |    1           |
        |    2           |    test11     |    0           |
        |    3           |    test12     |    0           |
        |    4           |    test13     |    0           |
        |    5           |    test14     |    0           |
        |    6           |    test2      |    2           |
        |    7           |    test21     |    0           |
        |    8           |    test22     |    0           |
        |    9           |    test23     |    0           |
        |    10          |    test24     |    0           |
        ---------------------------------------------------

预期输出为

        ---------------------------------------------------
        |    id               col1            col2        |
        ---------------------------------------------------
        |    1           |    test1      |    1           |
        |    2           |    test11     |    1           |
        |    3           |    test12     |    1           |
        |    4           |    test13     |    1           |
        |    5           |    test14     |    1           |
        |    6           |    test2      |    2           |
        |    7           |    test21     |    2           |
        |    8           |    test22     |    2           |
        |    9           |    test23     |    2           |
        |    10          |    test24     |    2           |
        ---------------------------------------------------

没有光标这可能吗?有没有一种方法可以在当前行值为 0 的情况下将顶行值添加到当前行值?

4

2 回答 2

4

您可以找到类似的最后一个非零值col2

select  id
,       col1
,       (
        select  top 1 col2
        from    YourTable yt2
        where   yt2.id <= yt1.id
                and yt2.col2 <> 0
        order by
                yt2.id desc
        )
from    YourTable yt1

SQL Fiddle 的示例。

于 2013-05-03T14:52:23.953 回答
0

看起来你不是在追逐一笔总和。这应该在 2005 年或以后工作:

DECLARE @tmp TABLE
    (
        id INT PRIMARY KEY
        , col1 VARCHAR(20)
        , col2 INT
    );
INSERT @tmp
VALUES
(1, 'test1',  1)
, (2, 'test11', 0)
, (3, 'test12', 0)
, (4, 'test13', 0)
, (5, 'test14', 0)
, (6, 'test2', 2)
, (7, 'test21', 0)
, (8, 'test22', 0)
, (9, 'test23', 0)
, (10, 'test24', 0);


SELECT 
    t1.id
    , t1.col1
    , CASE t1.col2
        WHEN 0 
            THEN t2.col2
        ELSE 
            t1.col2
    END col2
FROM 
    @tmp t1
OUTER APPLY
    (
        SELECT 
            TOP 1 col2
        FROM 
            @tmp t3
        WHERE 
            t3.id <= t1.id
            AND 
            t3.col2 > 0
        ORDER BY 
            t3.id DESC
    ) t2
于 2013-05-03T15:07:50.763 回答