I want to perform a self-join on the table to present the values column-wise. For each object, there are multiple properties (up to a known limit), but not all properties for all objects are stored. I have tried various joins but there are always missing rows and I want null values.
Starting table:
Object ID | Attributes | value |
---|---|---|
1 | one | 10 |
1 | b | 20 |
1 | c | 30 |
2 | one | 15 |
2 | c | 25 |
My goal (assuming I know the three possible properties are a,b,c
) is
Object ID | one | b | c |
---|---|---|---|
1 | 10 | 20 | 30 |
2 | 15 | 25 |
You can use the following query to achieve it:
illustrate:
Using the
CASE
statement, we select the value ofAttribute
as a specific value, i.e. "a", "b", etc. So for that particular column, only the value of that particular attribute is selected.Using
SUM
we aggregate the values ofValue
fields. This way, any multi-row value forObjectID
will be aggregated into a single row.If you are unwilling to use
SUM
because you may have non-numeric values, you can follow @xQbert's suggestion and useMAX
like this: