我的目标是同时拥有 HomeNumber 和 OfficeNumber 的一条记录,并且我保留 PersonID 以引用客户表。我在想我什至不应该使用 UNION 而可能是来自两个嵌套子查询的选择查询。
返回的结果如下所示。
1A370535-9432-45B9-8F08-004F040EE196 '' ''
1A370535-9432-45B9-8F08-004F040EE196 6127319561 ''
E8FA1667-416C-4639-ADDC-02143D651B4E '' 6512096719
E8FA1667-416C-4639-ADDC-02143D651B4E 6515786963 ''
这是我的查询:
SELECT PhoneNumbers.PersonID, PhoneNumbers.HomeNum, PhoneNumbers.OfficeNum
FROM (
SELECT PhoneHub.PersonID, ISNULL(PhoneHub.PhoneNbr, '') AS HomeNum, '' AS OfficeNum
FROM
--PhoneType INNER JOIN
PhoneHub --ON PhoneType.ID = PhoneHub.TypeID
WHERE
(PhoneHub.FranID = @FranID) AND
(PhoneHub.TypeID = '28321161-668e-4a56-90be-67a146fa1353') -- Home# ID
UNION
SELECT PhoneHub.PersonID, '' AS HomeNum, ISNULL(PhoneHub.PhoneNbr, '') AS OffNum
FROM
--PhoneType AS PhoneType_2 INNER JOIN
PhoneHub --AS PhoneHub ON PhoneType_2.ID = PhoneHub.TypeID
WHERE
(PhoneHub.FranID = @FranID) AND
(PhoneHub.TypeID = '02a4125b-b968-4dc6-9734-7f75f45f7635') --Office# ID
) AS PhoneNumbers
ORDER BY PhoneNumbers.PersonID
表架构 - PhoneHub
PK ID uniqueidentifier
FK FranID uniqueidentifier Franchise.ID
FK PersonID uniqueidentifier Customer.ID
FK TypeID uniqueidentifier PhoneType.ID
PhoneNbr nvarchar(20)
PhoneExt nvarchar(10)
IsDefault bit