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

MySQL self join with missing data

I’m wanting to perform a self-join on a table to present the values in a column wise manner. For each object there are several attributes (up to a known limit), but not all attributes are stored for all objects. I’ve tried various joins but I’m always getting missing rows, where I would like to have empty values instead.

Starting Table:

ObjectID Attribute Value
1 a 10
1 b 20
1 c 30
2 a 15
2 c 25

What I’m aiming for (given that I know the three possible attributes are a,b,c) is

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

ObjectID a b c
1 10 20 30
2 15 25

>Solution :

You can achieve it using following query:

SELECT
    ObjectID,  
    SUM(CASE WHEN Attribute = 'a' THEN Value ELSE NULL END) AS a,
    SUM(CASE WHEN Attribute = 'b' THEN Value ELSE NULL END) AS b,
    SUM(CASE WHEN Attribute = 'c' THEN Value ELSE NULL END) AS c
FROM mytable
GROUP BY ObjectID

Explaination:

Using CASE statement, we are selecting the value of Attribute for specific value i.e. ‘a’, ‘b’ etc. So that for that specific column, only value of that particular attribute is selected.

Using SUM we are aggregating the value of Value field. So that the value of multiple rows are being aggregated into a single row for any ObjectID.

In case you are not willing to use SUM as you may have non numeric values, you can use MAX as suggested by @xQbert like below:

SELECT
    ObjectID,  
    MAX(CASE WHEN Attribute = 'a' THEN Value ELSE NULL END) AS a,
    MAX(CASE WHEN Attribute = 'b' THEN Value ELSE NULL END) AS b,
    MAX(CASE WHEN Attribute = 'c' THEN Value ELSE NULL END) AS c
FROM mytable
GROUP BY ObjectID
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