I have a table called Contacts
that contains the columns
- Id
- FirstName
- LastName
I have another table called ContactsExtra
. It has the following columns:
- Id
- ContactId (FK refers to Contacts Id)
- PropertyId (FK refers to Properties Id)
- PropertyValue
This is a Key/Value table that stores some extra contact properties. E.g. if contact has a Salary property there is a record in this table for all Contacts that stores the Salary value.
All Properties (whether they are in the main Contacts
table or not) are stored in a separate table called Properties
. In this table, those properties that come from Contacts
(FirstName and LastName) are locked. But the user can add or remove custom properties (these ones are not locked). The value of these new properties will be stored in ContactsExtra
.
The Properties
table contains the following columns:
- Id
- Name
What I would like to do is to display all the contact information using one SELECT. So e.g. in the above case there will be a result with columns Id,FirstName,LastName and also Salary. The first three come from Contacts and the last comes from the Key/Value table. How can I join these information together?
Okay, here's the update with a PIVOT (not UNPIVOT as I first thought)...
Please check against your data - I expect the output to be something like...
The use of MAX is a bit of a kludge because it has to be an aggregate function there. The assumption is being made that there is only one value in the ContactsExtra table for each combination of user and property.