2

I need to update duplicate rows with different values in same table. my table is

table(id, phoneId(int), deviceId(int), userId(int))

There are some records with same deviceId or phoneId. for example

id   phoneId   deviceId    userId
1    23        3434        1235
2    23        5453        235   <---- same phoneId with 1 record 
3    43        5453        2343  <---- same deviceId with 2 record
4    23        3434        6347  <---- same deviceId and phoneID with 1 record

what i need to change is - if phoneId is not unique, set phoneId to userId(from this row). same at deviceId. (if deviceId is not unique, set deviceId to userId) so the final result should be this

id   phoneId   deviceId    userId
1    23        3434        1235
2    235       5453        235   <---- phoneId changed to userId
3    43        2343        2343  <---- phoneId changed to userId
4    6347      6347        6347  <---- phoneId and deviceId changed to userId
2
  • The problem is that you can get chains . . . P1 --> D1 --> P2 --> D2. What do you want to do about these? Commented Jul 25, 2017 at 14:08
  • sorry, can you please be more specific Commented Jul 25, 2017 at 14:11

1 Answer 1

4

Just update duplicated phoneids and then duplicated deviceids (assuming that table name is "t")

UPDATE t SET phoneid=userid FROM (SELECT count(*),phoneid FROM t GROUP BY phoneid HAVING count(*)>1) AS foo WHERE t.phoneid=foo.phoneid;
UPDATE t SET deviceid=userid FROM (SELECT count(*),deviceid FROM t GROUP BY deviceid HAVING count(*)>1) AS foo WHERE t.deviceid=foo.deviceid;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.