使用SQL Server

时间:2017-02-14 12:39:07

标签: sql-server left-join outer-join

我有一个父表“Employee”,员工信息存储在三个子表中,每个子表有一个子表。请考虑以下表格:

表:员工(Level#1)

EmpId    IsActive
__________________
1        1
2        1
3        1
4        0
5        0
6        1

表:EmployeeEmail(Level#2)

EmpEmailId    EmpId    EmailId
______________________________
1             1         1
2             4         3
3             6         4

表:EmailAddress(Level#3)

EmailId    Email
____________________________
1          one@gmail.com
2          two@gmail.com
3          three@gmail.com
4          four@gmail.com

表:EmployeePhone(Level#2)

EmpPhoneId    EmpId    PhoneId    Type
____________________________________________
1             1         1         Mobile
2             2         2         Mobile
3             5         4         Fax
4             1         6         Fax
5             2         9         Home

表:PhoneNumber(Level#3)

PhoneId    PhoneNumber
_______________________
1          9912345671
2          9912345672
3          9912345673
4          9912345674
5          9912345675
6          9912345676
7          9912345677
8          9912345678
9          9912345679

现在我需要选择活动员工记录(完整信息),如果员工有电话号码,那么它应该来,否则它应该是NULL,我也需要相同的电子邮件。

我的预期输出:

EmpId        Email             Home        Mobile        Fax
____________________________________________________________________
  1          one@gmail.com     NULL        9912345671    9912345676
(...)

此问题类似于我之前的问题How to effeciently SELECT Nested dependency Tables using JOIN in SQL Server

请帮助我如何获取一行中的多个电话号码

1 个答案:

答案 0 :(得分:0)

这是一个简单的case样式pivot,看起来很符合您的需求:

select 
      e.EmpId
    , Email  = max(em.Email)
    , Home   = max(case when ep.Type = 'Home'   then pn.PhoneNumber else null end)
    , Mobile = max(case when ep.Type = 'Mobile' then pn.PhoneNumber else null end)
    , Fax    = max(case when ep.Type = 'Fax'    then pn.PhoneNumber else null end)
  from Employee as e
    left join EmployeeEmail as ee on  e.EmpId   = ee.EmpId
    left join EmailAddress  as ea on ee.EmailId = ea.EmailId
    left join EmployeePhone as ep on  e.EmpId   = ep.EmpId
    left join PhoneNumber   as pn on ep.PhoneId = pn.PhoneId
  where e.IsActive = 1
  group by e.EmpId