两列的SQL PIVOT结果在所有数据透视列中都为空

时间:2018-09-01 14:59:12

标签: sql sql-server tsql

我正在尝试创建它:

Last Name, First Name, Email1, Email2, Email3, Phone1, Phone2, Phone3

此查询中:

;with CTE AS (
SELECT   FirstName, LastName, Email, Phone, Zip
FROM   Mother.dbo.People
Join   Mother.dbo.PeopleEmail on People.PeopleID = PeopleEmail.PeopleEmailID
Join   Mother.dbo.PeoplePhone on People.PeopleID = PeoplePhone.PeopleID
Where Zip IN ('34201','34202','34203','34205','34207','34208')
) Select * from CTE
PIVOT
(
       MAX(Email)
       FOR Email IN (Email1, Email2, Email3)
) AS E
PIVOT
(
        MAX(Phone)
        For Phone IN (Phone1, Phone2, Phone3)
) AS P;

但是,看来我的所有“电子邮件和电话”字段都返回空值。

作记录,

  1. 我正在使用SQL Server 2017
  2. 人员表具有名字和姓氏,并且与PeopleEmail(电子邮件字段)和PeoplePhone(电话字段)一对多。

我想念什么? 谢谢!

1 个答案:

答案 0 :(得分:0)

使用条件聚合可以更好。但是您需要枚举值才能对其进行透视:

select p.FirstName, p.LastName, Email, Phone, p.Zip
from Mother.dbo.People p join
     (select PeopleId,
             max(case when seqnum = 1 then email end) as email1,
             max(case when seqnum = 2 then email end) as email2,
             max(case when seqnum = 3 then phone end) as email3,
             max(case when seqnum = 1 then phone end) as phone1,
             max(case when seqnum = 2 then phone end) as phone2,
             max(case when seqnum = 3 then email end) as phone3
      from ((select pe.PeopleID, pe.email, null as phone,
                    row_number() over (partition by pe.PeopleID order by pe.PeopleEmailID) as seqnum
             from Mother.dbo.PeopleEmail pe
            ) union all
            (select pp.PeopleID, null as email, pp.phone,
                    row_number() over (partition by pp.PeopleID order by pp.PeoplePhoneId) as seqnum
             from Mother.dbo.PeopleEmail pe
            )
           ) em
      group by PeopleId
     ) em
     on p.PeopleID = em.PeopleEmailID
Where p.Zip IN ('34201', '34202', '34203', '34205', '34207', '34208');

编辑:

或者您也可以这样表达:

select p.FirstName, p.LastName, Email, Phone, p.Zip
       max(case when seqnum = 1 then email end) as email1,
       max(case when seqnum = 2 then email end) as email2,
       max(case when seqnum = 3 then phone end) as email3,
       max(case when seqnum = 1 then phone end) as phone1,
       max(case when seqnum = 2 then phone end) as phone2,
       max(case when seqnum = 3 then email end) as phone3
from ((select pe.PeopleID, pe.email, null as phone,
              row_number() over (partition by pe.PeopleID order by pe.PeopleEmailID) as seqnum
       from Mother.dbo.PeopleEmail pe
      ) union all
      (select pp.PeopleID, null as email, pp.phone,
              row_number() over (partition by pp.PeopleID order by pp.PeoplePhoneId) as seqnum
       from Mother.dbo.PeopleEmail pe
      )
     ) em join
     Mother.dbo.People p
     on p.PeopleID = em.PeopleEmailID
where p.Zip in ('34201', '34202', '34203', '34205', '34207', '34208');