0

我的目标是同时拥有 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 
4

2 回答 2

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
于 2012-11-02T18:12:37.657 回答
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
于 2012-11-02T18:23:20.083 回答