Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update one of 2 duplicates in an sql server database table

Tags:

sql

sql-server

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.. I want to add a 1 or an a to one of them and that will be for many other duplicates in the same column. Basically just add one number or letter to every 1 of the duplicates so there's no more duplicates.

I got this query that will update all the duplicates but not one of them. Can anyone help?

UPDATE Table1    SET Column1 = 'a'  WHERE exists        (SELECT Column1 , COUNT(Column1 ) FROM Clients GROUP BY Column1  HAVING ( COUNT(Column1 ) > 1) ) 
like image 336
MohammedT Avatar asked Jul 22 '13 09:07

MohammedT


People also ask

How do you UPDATE duplicates in SQL?

The Insert on Duplicate Key Update statement is the extension of the INSERT statement in MySQL. When we specify the ON DUPLICATE KEY UPDATE clause in a SQL statement and a row would cause duplicate error value in a UNIQUE or PRIMARY KEY index column, then updation of the existing row occurs.

How do you fix duplicates in SQL?

1) First identify the rows those satisfy the definition of duplicate and insert them into temp table, say #tableAll . 2) Select non-duplicate(single-rows) or distinct rows into temp table say #tableUnique. 3) Delete from source table joining #tableAll to delete the duplicates.

Can we UPDATE two values in SQL?

Can we UPDATE multiple tables with a single SQL query? No, only 1 table can be updated with an UPDATE statement.

Can I UPDATE 2 columns in SQL?

We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required.


2 Answers

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 
like image 97
Nithesh Narayanan Avatar answered Oct 17 '22 05:10

Nithesh Narayanan


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.

like image 24
Joachim Isaksson Avatar answered Oct 17 '22 05:10

Joachim Isaksson