2

我正在尝试使以下代码正常工作。我只想在有重复项时更新 TranID

update Test set TranID=(select MAX(TranID)+1 from Test)
from Test
group by TranID
having COUNT(TranID)>1
4

3 回答 3

1

尝试这个 :

    DECLARE @TranID INT = ( SELECT  MAX(TranID) 
                        FROM    Test
                      );
    WITH    List
          AS ( SELECT   ROW_NUMBER() OVER ( ORDER BY TranID ) + @TranID NewTranID ,
                        TranID
               FROM     Test T
               WHERE    T.TranID IN ( SELECT    T2.TranID
                                      FROM      Test T2
                                      GROUP BY  T2.TranID
                                      HAVING    COUNT(T2.TranID) > 1 )
             )
    UPDATE  List
    SET     TranID = NewTranID
于 2013-05-10T20:00:47.487 回答
0

在我的脑海中,这应该有效:

UPDATE Test
 SET TranID = (select MAX(TranID)+1 from Test)
FROM Test
  inner JOIN (SELECT TranID
             FROM Test 
             GROUP BY TranID
             HAVING COUNT(*) > 1) d ON d.TranID = Test.TranID
于 2013-05-10T19:32:47.827 回答
0

假设您只想为每个 TranID 匹配集更新除一个之外的所有内容,然后尝试此解决方案。

-- Setup your data
IF OBJECT_ID('Test', 'U') IS NOT NULL DROP TABLE Test;
CREATE TABLE Test (TranID int)
INSERT Test (TranID) VALUES (1),(2),(2),(3),(3),(3),(6),(6)
GO

DECLARE @MaxTranID int = (SELECT MAX(TranID) FROM Test)

;WITH test_temp (idx, TranID)
AS
(
    -- Get a unique identifier for each record
    SELECT ROW_NUMBER() OVER ( ORDER BY TranID ) as idx
          ,TranID
      FROM Test
)
,test_temp_dupes (TranID, MinIdx)
AS
(
    -- Get the first record in each TranID group
    SELECT TranID
          ,MIN(idx) as MinIdx
      FROM test_temp
     GROUP BY TranID
    HAVING COUNT(*) > 1
)

-- Assign new values to each TranID in the dupe groups except the first record
UPDATE A
   SET A.TranID = A.idx + @MaxTranID
  FROM test_temp A
  JOIN test_temp_dupes B
    ON A.TranID = B.TranID
   AND A.idx   <> B.MinIdx

-- See your results
SELECT * FROM Test
于 2013-05-14T05:30:07.627 回答