2017-02-06 69 views
-1
不同的目的

我的表是這樣的:如何檢索來自同一列中的記錄表使用聯接在SQL

EmployeeID FirstName LastName DateOfBirth MaritalStatus Gender Email InsertedDate UpdatedDate dateofjoining 
1 Sai Kumar 15/10/1993 Unmarried Male [email protected] 2014-01-01 2014-01-01 2014-01-02 00:00:00.000 
2 Venky rachipudi 16/10/1991 Unmarried male [email protected] 2014-02-02 2014-02-02 2014-02-02 00:00:00.000 
3 Manoj Kumar 16/10/1990 Married male [email protected] 2014-03-03 2014-03-03 2014-03-04 00:00:00.000 

二表

TeamID EmployeeID TeamLeadID ProjectID 
    1   1   3   1 
    2   2   3   2 
+4

很好的數據......你真正的問題是什麼? –

+0

我期待員工姓名和團隊負責人姓名從我的第一張桌子加入第二張桌子 –

回答

0

你可以做兩連接得到輸出你想要的:

SELECT COALESCE(e1.LastName, 'NA') + ', ' + COALESCE(e1.FirstName, 'NA') AS employee_name, 
     COALESCE(e2.LastName, 'NA') + ', ' + COALESCE(e2.FirstName, 'NA') AS team_lead_name 
FROM table2 t2 
LEFT JOIN employees e1 
    ON t2.EmployeeID = e1.EmployeeID 
LEFT JOIN employees e2 
    ON t2.TeamLeadID = e2.EmployeeID 

這裏table2是你標記second table在你的問題中,employees是第一個包含每個員工(包括團隊領導)信息的表格。

+1

非常感謝您的完美工作 –

0
select t1.firstname + ' ' + t1.lastname as EmployeeName, 
     t3.firstname + ' ' + t3.lastname as LeaderName 
From t1 left join (select distinct EmployeeID,TeamLeadID from t2) t2 on 
    t1.EmployeeID = t2.EmployeeID left join t2 as t3 on 
    t2.EmployeeID = t3.EmployeeID 

希望這是你在找什麼。

+0

它在t3的顯示錯誤請檢查它。謝謝你的回覆 –

相關問題