2013-05-10 45 views
2

組中的having子句的結果執行更新我試圖讓下面的代碼工作。我想更新TranID只要有重複如何根據

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

表格是否有更多列?我假設你想避免由更新引起的重複'TranID'?請顯示示例dara和期望的結果。 – 2013-05-10 19:25:36

+0

請爲您的表發佈「CREATE TABLE」語句 – peterm 2013-05-10 19:30:03

回答

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 
+0

非常感謝Behrouz,這很有效 – 2013-05-20 15:09:41

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 
+0

這會更新與完全相同的值匹配的所有內容。 – 2013-05-14 04:27:00

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