[英]Join master table's data to a key/value table data in one SELECT
I have a table called Contacts
that contains the columns 我有一个名为Contacts
的表,其中包含各列
I have another table called ContactsExtra
. 我有另一个名为ContactsExtra
表。 It has the following columns: 它包含以下列:
This is a Key/Value table that stores some extra contact properties. 这是一个键/值表,其中存储了一些额外的联系人属性。 Eg 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
. 所有属性(无论它们是否在主Contacts
表中)都存储在称为Properties
的单独表中。 In this table, those properties that come from Contacts
(FirstName and LastName) are locked. 在此表中,来自“ Contacts
(名字和姓氏)的那些属性被锁定。 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
. 这些新属性的值将存储在ContactsExtra
。
The Properties
table contains the following columns: Properties
表包含以下列:
What I would like to do is to display all the contact information using one SELECT. 我想做的是使用一个SELECT显示所有联系信息。 So eg in the above case there will be a result with columns Id , FirstName , LastName and also Salary . 因此,例如在上述情况下,结果将包含列Id , FirstName , LastName以及Salary 。 The first three come from Contacts and the last comes from the Key/Value table. 前三个来自“联系人”,最后三个来自“键/值”表。 How can I join these information together? 如何将这些信息整合在一起?
SELECT
Contacts.FirstName,
Contacts.LastName,
Properties.Name,
ContactsExtra.PropertyValue
FROM
Contacts
LEFT OUTER JOIN ContactsExtra ON Contacts.Id = ContactsExtra.ContactId
LEFT OUTER JOIN Properties ON ContactsExtra.PropertyId = Properties.Id
Okay, here's the update with a PIVOT (not UNPIVOT as I first thought)... 好的,这是PIVOT(不是我最初想到的UNPIVOT)的更新...
SELECT
*
FROM
(
SELECT
Contacts.FirstName,
Contacts.LastName,
Properties.Name,
ContactsExtra.PropertyValue
FROM
Contacts
LEFT OUTER JOIN ContactsExtra ON Contacts.Id = ContactsExtra.ContactId
LEFT OUTER JOIN Properties ON ContactsExtra.PropertyId = Properties.Id
) DerivedPivotable
PIVOT
(
MAX(PropertyValue)
FOR [Name] IN (<comma delimited list of values from your Properties.Name field, without string markup>)
--FOR [Name] IN (Salary, Height, Status, SSN) --example row
) Pivoted
Please check against your data - I expect the output to be something like... 请对照您的数据进行检查-我希望输出结果类似于...
FirstName LastName Salary Height Status SSN
-----------------------------------------------------------
Jane Doe NULL 5'7" Single NULL
Bob Smith 70,000 6'1" NULL 123-45-6789
The use of MAX is a bit of a kludge because it has to be an aggregate function there. 使用MAX有点麻烦,因为它必须是那里的聚合函数。 The assumption is being made that there is only one value in the ContactsExtra table for each combination of user and property. 假设在ContactsExtra表中对于用户和属性的每种组合只有一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.