Pivot输出两个值

时间:2017-05-19 21:57:49

标签: sql tsql pivot sql-server-2014

create table #Contact(
 LoanNumber int,
 ContactType varchar(10),
 CompanyName varchar(10),
 CompanyPhone varchar(10),
 CONSTRAINT PK PRIMARY KEY (LoanNumber,ContactType)
)

Insert into #Contact
values (1,'Appriaser','Yige King','11' ),
       (1,'AssetOwner','gqqnbig','22' )

这是我的桌子。 ContactTypes只是Appriaser和AssetOwner。

enter image description here

我可以获得像

这样的表格吗?
LoanNumber  AppraiserCompanyName    AppraiserCompanyPhone   AssertOwnerCompanyName  AssertOwnerCompanyPhone
----------------------------------------------------------------------------------------------------
6103339     YigeKing                11                      gqqnbig                 22

我设法写了这个

select LoanNumber,
        CompanyNamePT.Appriaser as AppriaserCompanyName, CompanyNamePT.AssetOwner as AssetOwnerCompanyName
        --CompanyPhonePT.Appriaser as AppriaserCompanyPhone, CompanyPhonePT.AssetOwner as AssetOwnerCompanyPhone
from  (
    select #contact.LoanNumber, #contact.ContactType, #contact.CompanyName
    from #contact
) as c
pivot ( max(c.CompanyName) for c.ContactType in (Appriaser,AssetOwner)) as CompanyNamePT
--pivot ( max(c.CompanyPhone) for c.ContactType in ([Appriaser],[AssetOwner])) as CompanyPhonePT

它会输出公司名称,但如果我取消注释这两行以获取电话号码,则会引发语法错误。

我怎样才能让它发挥作用?理想情况下,我想使用数据透视,因为我正在学习它。

1 个答案:

答案 0 :(得分:1)

对于所需的PIVOT

Select *
 From (
        Select C.LoanNumber
              ,B.*
         From  #Contact C
         Cross Apply ( values (IIF(ContactType='Appriaser'  ,'AppraiserCompanyName' , 'AssetOwnerCompanyName') ,C.CompanyName)
                             ,(IIF(ContactType='Appriaser' , 'AppraiserCompanyPhone', 'AssetOwnerCompanyPhone'),C.CompanyPhone)
                     ) B (Item,Value)
      ) A
pivot ( max(A.Value) for A.Item in ([AppraiserCompanyName],[AppraiserCompanyPhone],[AssetOwnerCompanyName],[AssetOwnerCompanyPhone]) ) P

但条件聚合也可以

Select C.LoanNumber
      ,AppraiserCompanyName   =  max(case when ContactType='Appriaser'  then C.CompanyName end)
      ,AppraiserCompanyPhone  =  max(case when ContactType='Appriaser'  then C.CompanyPhone end)
      ,AssetOwnerCompanyName  =  max(case when ContactType='AssetOwner' then C.CompanyName end)
      ,AssetOwnerCompanyPhone =  max(case when ContactType='AssetOwner' then C.CompanyPhone end)
From #Contact C
Group By C.LoanNumber

两者都会返回

enter image description here

如果它有助于可视化,则使用“交叉应用生成”的子查询

enter image description here