左外连接多个选择

时间:2018-04-20 18:51:15

标签: sql sql-server tsql select

我有以下sql语句,它完全按照它应该做的:

select    C.Company_RecID, C.Contact_RecID, C.First_Name, C.Last_Name,
          C.Title, C.Inactive_Flag, e.Description
FROM            dbo.Contact AS C 
LEFT OUTER JOIN dbo.Contact_Communication AS e ON C.Contact_RecID = e.Contact_RecID 
                                AND e.Communication_Type_RecID = 1 AND e.Default_Flag = 1

但是,在dbo.contact_communication中,description字段表示不同的内容,具体取决于communication_type_recID。如果是1,则说明是电子邮件地址。如果是4,则为手机号码,如果是2,则为直接号码,如果是14,则为个人手机号码。

我想更改查询以返回另外三列。第8列将是描述的值,如果此联系人的记录为recid为4,则第9列为描述值,如果此联系人的记录为recid为2,则第10列为值(如果有值) 14。

3 个答案:

答案 0 :(得分:1)

这样的事情应该非常接近,因为我明白你在寻找什么。

select C.Company_RecID
    , C.Contact_RecID
    , C.First_Name
    , C.Last_Name
    , C.Title
    , C.Inactive_Flag
    , e.Description
    , EmailAddress = MAX(case when communication_type_recID = 1 then e.Description end)
    , CellPhone = MAX(case when communication_type_recID = 4 then e.Description end)
    , DirectNumber = MAX(case when communication_type_recID = 2 then e.Description end)
    , PersonalCellPhone = MAX(case when communication_type_recID = 14 then e.Description end)
FROM dbo.Contact AS C 
LEFT OUTER JOIN dbo.Contact_Communication AS e ON C.Contact_RecID = e.Contact_RecID 
                                        AND e.Communication_Type_RecID IN (1,2,4,14) 
                                        AND e.Default_Flag = 1
group by C.Company_RecID
    , C.Contact_RecID
    , C.First_Name
    , C.Last_Name
    , C.Title
    , C.Inactive_Flag
    , e.Description

答案 1 :(得分:0)

我认为UNION可能会帮助你。 (https://docs.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql?view=sql-server-2017

您可以尝试这样的事情:

select col_1, 'something' as A, '' as B from TableA
union
select col_2, '' as A, 'something' as B from TableA

col_1和col_2是表中的实际列,而A和B是此额外信息的别名。

答案 2 :(得分:0)

没有聚合

select C.Company_RecID
     , C.Contact_RecID
     , C.First_Name
     , C.Last_Name
     , C.Title
     , C.Inactive_Flag
     , e.Description
     , e1.Description  as EmailAddress
     , e2.Description  as CellPhone
     , e4.Description  as DirectNumber
     , e14.Description as PersonalCellPhone 
  FROM dbo.Contact AS C 
  LEFT OUTER JOIN dbo.Contact_Communication AS e1 
    ON e1.Contact_RecID = C.Contact_RecID   
   AND e1.Communication_Type_RecID = 1 
   AND e1.Default_Flag = 1
 LEFT OUTER JOIN dbo.Contact_Communication AS e2 
    ON e2.Contact_RecID = C.Contact_RecID   
   AND e2.Communication_Type_RecID = 2
   AND e2.Default_Flag = 1
  LEFT OUTER JOIN dbo.Contact_Communication AS e4 
    ON e4.Contact_RecID = C.Contact_RecID   
   AND e4.Communication_Type_RecID = 4 
   AND e4.Default_Flag = 1
  LEFT OUTER JOIN dbo.Contact_Communication AS e14 
    ON e14.Contact_RecID = C.Contact_RecID   
   AND e14.Communication_Type_RecID = 14  
   AND e14.Default_Flag = 1