Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to move duplicate IDs to seperate column

I have a mySQL table with two duplicate names, how can I seperate the IDs of the duplicate names into a seperate column?

   ---------------------------------
   | id   | name       | surname   |
   ---------------------------------     
   |  557 | Logan      | Smith     |
   | 1052 | Logan      | Smith     |
   ---------------------------------

For example, like this:

   ----------------------------------------
   | id   |  id2  | name      | surname   |
   ----------------------------------------     
   | 557  |  1052 | Logan     | Smith     |
   ----------------------------------------

This is my current SQL statement to retrieve the current results in the first table:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT userid as id, name, surname
FROM user
WHERE name = "Logan"
GROUP BY userid

There is only one duplicate at most for each name.

Thanks

>Solution :

If you are sure that the maximum is always 2… then you could:

SELECT min(userid) as id1, max(userid) as id2, name, surname
FROM user
WHERE name = "Logan"
GROUP BY name, surname

If you want to sofisticate a little bit more the query

SELECT min(userid) as id1,
  case when min(userId) = max(userid) then null else max(userId) end as id2, name, surname
FROM user
WHERE name = "Logan"
GROUP BY name, surname
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading