2015-04-02 74 views
0

我使用MS SQL Server 2008 R2。如何設置上一行的列值?

enter image description here

是否有可能設置條形碼列的值與StatusID = 3到行與StatusID = 10

+0

哪一列是您的訂購欄? – 2015-04-02 08:05:09

+0

這是另一列 - 創建,它不顯示在屏幕截圖中。 – tesicg 2015-04-02 08:09:57

回答

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 
相關問題