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 can I normalize a MySQL table that contains NULLs in some fields for some records but not all?

I have a non-normalized table that’s arisen from joining three different tables together that are joining against the PrimaryId field. Most fields have valid values for all fields, but some are missing values in identifiers

PrimaryId, Name, Internal_System_One_Identifier, Internal_System_Two_Identifier, 
abc123, 'Joes Supermarket', '22e0b9f6', NULL
abc123, 'Joes Supermarket', NULL, '22e0b9f8'
abc124, 'Suzannas Coffee', '22e0ba6c', NULL
abc124, 'Suzannas Coffee', '22e0ba6c', '22e0ba6e'
abc125, 'Rogers Aquatics', NULL, '22e0ba6c'
abc125, 'Rogers Aquatics', '22e0ba6e', '22e0ba6c'
abc126, 'Frankies Records', NULL, NULL
abc127, 'Henrys Hammers', '22e0bb7d','22e0bb7e'

And I want to normalize it to

abc123, Joe's Supermarket, ac341d-4a4fe9, 9db37d-8e5g73
abc124, 'Suzannas Coffee', '22e0ba6c', '22e0ba6c'
abc125, 'Rogers Aquatics', '22e0ba6e', '22e0ba6c'
abc126, 'Frankies Records', NULL, NULL
abc127, 'Henrys Hammers', '22e0bb7d','22e0bb7e'

But I can’t figure out how to do this at all. I feel like I should use something like a coalesce function or window function, but I can’t understand how I would do that.

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

>Solution :

You could group by the primary ID and the name, and use max on the other two identifiers in order to eliminate nulls:

SELECT    PrimaryId,
          Name,
          MAX(Internal_System_One_Identifier),
          MAX(Internal_System_Two_Identifier)
FROM      mytable
GROUP BY PrimaryId, Name
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