我使用的是MS SQL Server 2008 R2。
是否可以将StatusID = 3的行中的BarCode列的值设置为具有StatusID = 10的BarCode的行中的相同值。
答案 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