Consider the example below where I have a Person table containing person records and a PersonAttribute table which contains optional attributes linked to a person:
Table: Person
ID Name 1 Joe Bloggs 2 Jane Doe
Table PersonAttribute
PersonId Key Value 1 Age 27 2 HairColor Brown
How would I write a query that returns all people with the attributes as if they were columns? The resultset I require is:
ID Name Age HairColor 1 Joe Bloggs 27 2 Jane Doe Brown
So essentially I need to write a query that gets all Person Records with all unique Attribute Keys transposed as columns with the value for each person record.
Note that the primary key on the PersonAttribute table is PersonID and Key combined so we wont have duplicate entries for a specific key and person.
Obviously I could add the Age and HairColor as fields in the Person table and not use the PersonAttribute table at all, but this is just an example to illustrate the problem. In reality I have a huge number of custom attributes that vary wildly for different person records so it is not practical to do it that way.
I can’t speak about MySQL, but in PostgreSQL you could use crosstab function from tablefunc module:
Join query:
Wanted result:
As you see I put explicit list of columns in
PersonAttributePivotview. I don’t know any “automatic-pivot” creation way with implicit column list.EDIT:
For huge column list (assuming always
texttype) as a workaround I see such little modified approach:Dynamic type creation (here trivially Java based):
Result:
Function wrapper:
Automatic view creation:
Result: