难以在SQL Server查询中加入开发人员名称和测试人员名称

时间:2015-10-15 02:01:40

标签: sql sql-server

有一个employee表,其中包含以下列:

eno 
ename 
desig 

还有一个project表,列是:

pid 
pname 
devId 
tesid

Employee

+--------+----------+-----------+
|   Eno  | ename    | desig     |
+--------+----------+-----------+
| 1001   | Ramesh   | Developer |
+--------+----------+-----------+
| 1002   | Senthil  | Tester    |
+--------+----------+-----------+
| INV003 | Suresh   | Developer |
+--------+----------+-----------+

Project

+-----+----------+-------+---------+
| PID | PName    | DevID | TesName |
+-----+----------+-------+---------+
| P01 | Project1 | 1001  | 1002    |
+-----+----------+-------+---------+
| P02 | Project2 | 1003  | 1002    |
+-----+----------+-------+---------+

我需要结果集如下所示:join

+-----+----------+---------+----------+
| PID | PName    | DevName | TestName |
+-----+----------+---------+----------+
| P01 | Project1 | Ramesh  | Senthil  |
+-----+----------+---------+----------+
| P02 | Project2 | Suresh  | Senthil  |
+-----+----------+---------+----------+

我尝试使用内部联接,但我只能获得开发者名称。我如何加入测试名称?

1 个答案:

答案 0 :(得分:4)

您必须两次加入Employee表。只需为每个表添加一个别名。见下文

Select 
    PID,
    PName, 
    dev.ename as 'DevName',
    test.ename as 'TestName'
FROM Project proj
LEFT JOIN Employee dev 
    on dev.Eno = proj.PID
LEFT JOIN Employee test
    on proj.TestName= test.Eno