2017-02-14 25 views
1

我有一個父表「Employee」,員工信息存儲在三個子表中,每個子表都有一個子表。考慮下面的表:使用SQL服務器中的連接在單行中高效選擇嵌套的依賴關係表和多列

表:僱員(等級#1)

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

表:EmployeeEmail(級別#2)

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

表:EmailAddress的(等級#3)

EmailId Email 
____________________________ 
1   [email protected] 
2   [email protected] 
3   [email protected] 
4   [email protected] 

表:EmployeePhone(等級#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 

表:******中國(等級#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   [email protected]  NULL  9912345671 9912345676 
(...) 

這個問題是類似我剛纔的問題How to effeciently SELECT Nested dependency Tables using JOIN in SQL Server

請幫助我如何在單行獲取多個電話號碼?

回答

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