Update one of 2 duplicates in an sql server database table

前端 未结 11 1211
长发绾君心
长发绾君心 2020-12-05 00:48

I have got a table that got a column with duplicate values. I would like to update one of a 2 duplicate values so for example row1 = tom and row2 = tom

相关标签:
11条回答
  • 2020-12-05 01:06

    Try This with CTE and PARTITION BY

    ;WITH cte AS
    (
      SELECT
          ROW_NUMBER() OVER(PARTITION BY Column1  ORDER BY Column1 ) AS rno,
          Column1 
      FROM Clients
    )
    
    UPDATE cte SET Column1 =Column1 +' 1 '
    WHERE rno=2
    
    0 讨论(0)
  • 2020-12-05 01:06

    Using sub-queries might work:

    UPDATE table1
    SET STATUS = 'F'
    WHERE column1= 
       (SELECT (column1)
        FROM table1
        GROUP BY column1 
        HAVING (COUNT(column1 ) > 1))
    
    0 讨论(0)
  • 2020-12-05 01:07

    Try this mate

    UPDATE Table1 
    SET Column1 = column1 +'a'   
    WHERE exists(
            select row 
            from (
                SELECT 
                    Column1 , 
                    Row_Number() over(Partition by Column1 order by Column1) as row 
                FROM Clients
            ) as subquery 
            where subquery.row = 2
        )
    
    0 讨论(0)
  • 2020-12-05 01:08

    I think you can use TOP() operator instead of row_number() method it will help you to update one in easy and simple way

    UPDATE TOP ( 1 )Table1 SET Column1 = 'a';
    
    0 讨论(0)
  • 2020-12-05 01:15

    Assume Table1, containing the following information:

    Column1      
    ========  
    tom        
    john   
    jack    
    tom     
    james
    jane 
    

    Notice that the first and fourth rows are identical. Here's the UPDATE command to change the name in only one of them.

    UPDATE Table1 AS t1
       SET Column1 = 'jennifer'
     WHERE rrn(t1) =
           (SELECT MAX(rrn(t2))
              FROM Table1 AS t2
             WHERE Column1 = 'tom')
    

    And the result would be

    Column1      
    ========  
    tom        
    john   
    jack    
    jennifer
    james
    jane 
    

    with RRN function you can update the last occurance of duplicate record

    0 讨论(0)
  • 2020-12-05 01:17

    I think this simple update is what you're looking for;

    UPDATE Table1 SET Column1=Column1+CAST(id AS VARCHAR)
    WHERE id NOT IN (
      SELECT MIN(id) 
      FROM Table1
      GROUP BY Column1
    );
    

    Input:

    (1,'A'),
    (2,'B'),
    (3,'A'),
    (4,'C'),
    (5,'C'),
    (6,'A');
    

    Output:

    (1,'A'),
    (2,'B'),
    (3,'A3'),
    (4,'C'),
    (5,'C5'),
    (6,'A6');
    

    An SQLfiddle to test with.

    0 讨论(0)
提交回复
热议问题