我的目标是拥有HomeNumber&amp ;; OfficeNumber和我保持PersonID引用customer表。我想我甚至不应该使用UNION,但可能是来自两个嵌套子查询的select查询。
返回的结果如下所示。
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
答案 0 :(得分:1)
这看起来像一个支点要求。
SELECT PersonID,
Max(case when TypeID = '28321161-668e-4a56-90be-67a146fa1353'
then PhoneNbr End) HomeNum,
Max(case when TypeID = '02a4125b-b968-4dc6-9734-7f75f45f7635'
then PhoneNbr End) OfficeNum
FROM
PhoneHub
WHERE
PhoneHub.FranID = @FranID
GROUP BY PersonID
答案 1 :(得分:0)
Select a.PersonID,Coalesce(home.PhoneNbr, '') AS HomeNum,Coalesce(office.PhoneNbr, '') AS OffNum from
(
SELECT PhoneHub.PersonID
FROM
PhoneHub
WHERE
(PhoneHub.FranID = @FranID) AND
(PhoneHub.TypeID = '28321161-668e-4a56-90be-67a146fa1353')
UNION
SELECT PhoneHub.PersonID
FROM
PhoneHub
WHERE
(PhoneHub.FranID = @FranID) AND
(PhoneHub.TypeID = '02a4125b-b968-4dc6-9734-7f75f45f7635')
) as a
left join PhoneHub home on (home.PersonID = a.PersonID) and (home.FranID = @FranID) AND (home.TypeID = '28321161-668e-4a56-90be-67a146fa1353')
left join PhoneHub office on (office.PersonID = a.PersonID) and (office.FranID = @FranID) AND (office.TypeID = '02a4125b-b968-4dc6-9734-7f75f45f7635')
order by a.PersonID