如何设置上一行的列值?

时间:2015-04-02 07:48:05

标签: sql-server-2008

我使用的是MS SQL Server 2008 R2。

enter image description here

是否可以将StatusID = 3的行中的BarCode列的值设置为具有StatusID = 10的BarCode的行中的相同值。

1 个答案:

答案 0 :(得分:0)

试试这个:

DECLARE @t TABLE
    (
      StatusID INT ,
      UserID INT ,
      BarCode CHAR(10)
    )

INSERT  INTO @t
VALUES  ( 1, 3378, '-1' ),
        ( 2, 3378, '-1' ),
        ( 10, 3378, 'some_code1' ),
        ( 1, 3379, '-1' ),
        ( 3, 3379, '-1' ),
        ( 10, 3379, 'some_code2' );
WITH    cte
          AS ( SELECT   StatusID ,
                        UserID ,
                        BarCode ,
                        ROW_NUMBER() OVER ( PARTITION BY UserID ORDER BY StatusID ) AS rn
               FROM     @t
             )
    UPDATE  c1
    SET     BarCode = c2.BarCode
    FROM    cte c1
            JOIN cte c2 ON c1.UserID = c2.UserID
                           AND c1.rn + 1 = c2.rn
    WHERE   c2.StatusID = 10
            AND c1.StatusID = 3

SELECT  * FROM    @t

输出:

StatusID    UserID  BarCode
1           3378    -1        
2           3378    -1        
10          3378    some_code1
1           3379    -1        
3           3379    some_code2
10          3379    some_code2