Update one of 2 duplicates in an sql server database table

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

    If we have this condition:

    SELECT Column1 FROM Clients ORDER BY Column1
    
    Column1
    **********
    Jhon
    Jhon
    Mike
    Mike
    Mike
    Robert
    

    This will work even if Column1 was duplicated n times, it will append the row number to every duplicate row except the first, try this:

    BEGIN 
    
    ;WITH CTE AS 
    (
        SELECT 
            ROW_NUMBER() OVER (PARTITION BY Column1 ORDER BY Column1) AS ROWNUMBER,
            Column1
        FROM Clients
    )
    
    UPDATE CTE 
    SET Column1 = CONCAT(Column1, ' ', (ROWNUMBER - 1))
    WHERE ROWNUMBER > 1
    
    SELECT Column1 FROM Clients ORDER BY Column1
    
    END 
    

    Result:

    Column1
    ***********
    Jhon
    Jhon 1
    Mike
    Mike 1
    Mike 2
    Robert
    
    0 讨论(0)
  • 2020-12-05 01:22

    I had to put the with inside a from since my sql developer didnt like updating a with Copying from the answer from Nithesh

    it ended up looking like this:

    UPDATE Clients 
    SET Column1 = 'a'
    WHERE ColumnID IN (select ColumnID from 
     (  
     SELECT
           row_number() OVER(PARTITION BY Column1  ORDER BY Column1 ) AS rno,
           ColumnID FROM Clients
     )
                       where rno=2   
                      )
    
    0 讨论(0)
  • 2020-12-05 01:23

    I have found this solution:

    My table devices already have data and the "serial" column should be unique. The "id" is a primary key. A random 6 digits value is concatenated after the original value.

    UPDATE devices 
    SET serial=CONCAT(serial,'_',LPAD(FLOOR(RAND() * 999999.99), 6, '0'))    
        where id in 
        (select * FROM( 
            SELECT d1.id as id 
            FROM devices as d1, devices as d2 
            WHERE d1.id <> d2.id and d1.serial=d2.serial) as subdevices
        )
    
    0 讨论(0)
  • 2020-12-05 01:25

    try this

    with test as 
    (
       select ROW_NUMBER() over (order by salary)rr, salary , emp_no 
       from salary
    )update test set emp_no=10007 where emp_no='10002'  and rr=3
    
    0 讨论(0)
  • 2020-12-05 01:27
    update wmwhse1.sku
    set descr= concat (descr,'.')
    where exists
    (select SKU,count (DESCR)
    from wmwhse1.sku
    group by descr
    having (count (DESCR)>1))
    

    all sku description is updating when I run this script.

    output: only 1 row should be affected

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