Question

I have a table with sample data as below:

Name   | Code
Ken      Ken_A
Ken      Ken_B
Tim      Tim_1
Tim      Tim_3
Sam      Sam_Tens
Sam      Sam_Tenson

I want to do an update query that replaces the second instance of the Code ordered by Name with the first instance, so I would end up with the below:

Name   | Code
Ken      Ken_A
Ken      Ken_A
Tim      Tim_1
Tim      Tim_1
Sam      Sam_Tens
Sam      Sam_Tens
Was it helpful?

Solution

Assuming that you have a column that specifies the ordering, you can use an updatable CTE with a join:

with toupdate as (
      select t.*, row_number() over (partition by name order by id) as seqnum
      from t
     )
update toupdate
    set code = tu2.code
    from toupdate join
         toupdate tu2
         on toupdate.name = tu2.name and
            tu2.seqnum = 1 and
            toupdate.seqnum > 1;

If you don't have a column that identifies the ordering of the rows, then your question doesn't make sense. In SQL, tables are inherently unordered.

OTHER TIPS

One option:

update mytable 
set code = (select min(code) from mytable min_name where min_name.name = mytable.name);

You could use this query which uses correlated sub-queries:

UPDATE t1 SET Code = (SELECT TOP 1 t2.Code FROM dbo.TableName t2
                      WHERE t1.Name = t2.Name
                      ORDER BY Name, Code)
FROM dbo.TableName t1
WHERE (SELECT COUNT(*) FROM dbo.TableName t2
       WHERE t1.Name = t2.Name) > 1

Demo

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top