I have a Person table and an attribute table. An Person can have 0 or more attributes, so I have this relationship stored in an intermediary key-value table, eg
------------ -------------- ---------------
|Person | |key val tbl | | attribute |
----------- -------------- ---------------
|p_id|p_name| | p_id |a_id | | a_id |a_name|
| 1 |simon | | 1 | 1 | | 1 | tall |
| 2 |eric | | 1 | 2 | | 2 | cool |
| 2 | 2 |
How could I write a query to return something like this?
|name |attr1|attr2|
|simon|tall |cool |
|eric | |cool |
There are only ~6 attributes and that will not likely change.
Thanks!
You need to join and aggregate:
This query joins the three tables together, which will produce a table with one row for each person/attribute pair. The final group by aggregates at the person level, “pivoting” the attributes across the row. The max(case …) expression simply chooses the value of attribute for column .