Update one of 2 duplicates in an sql server database table

前端 未结 11 1228
长发绾君心
长发绾君心 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: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

提交回复
热议问题