我有以下声明:
SELECT
Person.PersonID, Person.PersonName, Person.Surname,
Address.Street, Address.PostCode,
(SELECT Phones.Num
WHERE (Phones.CommunicationTypeId = '78')) AS email,
(SELECT Phones.Num
WHERE (Phones.CommunicationTypeId = '83')) AS mobile,
(SELECT Phones.Num
WHERE (Phones.CommunicationTypeId = '88')) AS phone
FROM
Address
RIGHT OUTER JOIN
Person ON Address.ObjectId = Person.PersonID
RIGHT OUTER JOIN
Phones ON Person.PersonID = Phones.ObjectID
现在结果显示了单独的行,而我想将它放在一行中:
如何将其合并为一行?
答案 0 :(得分:1)
看起来你的人有多个相应的电话记录(我想有两种不同类型的记录。
SELECT
ObjectID,
MAX(CASE WHEN CommunicationTypeId = '78' THEN Num ELSE null END) as email,
MAX(CASE WHEN CommunicationTypeId = '83' THEN Num ELSE null END) as mobile,
MAX(CASE WHEN CommunicationTypeId = '88' THEN Num ELSE null END) as phone
FROM Phones
GROUP BY ObjectID
上面的选择为每个人返回3列,您可以在主查询中使用它
SELECT
Person.PersonID, Person.PersonName, Person.Surname,
Address.Street, Address.PostCode,
Phones.email, Phones mobile, Phones.phone
FROM
Address
RIGHT OUTER JOIN
Person ON Address.ObjectId = Person.PersonID
RIGHT OUTER JOIN
(sub query above) Phones ON Person.PersonID = Phones.ObjectID