开发者

SQL: pointing a duplicate data

开发者 https://www.devze.com 2023-04-04 01:49 出处:网络
I have a tableA ID col1 col2 status 1ABC123NULL 2ABC214NULL 3BCA001NULL 4ABC123NULL 5BWE765NULL 6ABC123NULL 7BCA001NULL

I have a tableA

ID col1 col2 status
1  ABC  123   NULL
2  ABC  214   NULL
3  BCA  001   NULL
4  ABC  123   NULL
5  BWE  765   NULL
6  ABC  123   NULL
7  BCA  001   NULL

I want to flag the duplicate data (col1, col2) & populate the column=status with a message referring to the ID of which is du开发者_JS百科plicate. For example, ID=4 is duplicate of ID = 1 , ID=6 is duplicate of ID = 1 and ID 7 is duplicate of ID = 3. status = "Duplicate of ID = (ID here) " Expected result:

    ID col1 col2  status
    1  ABC  123   NULL
    2  ABC  214   NULL
    3  BCA  001   NULL
    4  ABC  123   Duplicate of ID = 1
    5  BWE  765   NULL
    6  ABC  123   Duplicate of ID = 1
    7  BCA  001   Duplicate of ID = 3

I can able to flag the duplicates but cant able to point then to the ID numbers. The script I used is :

WITH CTE_Duplicates1 AS
  (SELECT ROW_NUMBER() OVER (PARTITION BY col1,col2 
    ORDER BY (SELECT 0)) RN,Status
  FROM tableA 
  )
 UPDATE CTE_Duplicates1
 SET qnxtStatus = 'Duplicate of ID ='
 WHERE RN<>1 

Please correct. Thanks


;WITH CTE_Duplicates1 AS
(
SELECT MIN(ID) OVER (PARTITION BY col1, col2) Mn,
       ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY ID) Rn,
       *
FROM tableA       
)
UPDATE CTE_Duplicates1
SET qnxtStatus = 'Duplicate of ID =' + CAST(Mn AS VARCHAR(11))
WHERE Rn > 1
0

精彩评论

暂无评论...
验证码 换一张
取 消