SQL Query基于前两列返回新列

时间:2017-07-06 19:17:52

标签: sql

我有一个看起来像这样的表:

username    manager  
emp001      emp006   
emp002      emp006  
emp003      emp006   
emp004      emp007  
emp005      emp007   
emp006      emp009   
emp007      emp010    
emp008      emp010   
emp009      emp011      
emp010      null      
emp011      null

我想创建一个返回第三列的select查询 - 其中新列基于管理器项并返回第一列并获取该行的管理器。

username    manager    director
emp001      emp006     emp009             
emp002      emp006     emp009  
emp003      emp006     emp009   
emp004      emp007     emp010  
emp005      emp007     emp010   
emp006      emp009     emp011   
emp007      emp010     null   
emp008      emp010     null    
emp009      emp011     null    
emp010      null       null
emp011      null       null

我迷失了这个。

感谢您的任何建议。我尝试了各种选择和连接的组合,但似乎没有什么做我想要的。

谢谢!

3 个答案:

答案 0 :(得分:1)

这应该做你想要的:

Select      E.UserName, E.Manager, M.Manager As Director
From        YourTable   E
Left Join   YourTable   M   On  E.Manager = M.UserName

答案 1 :(得分:0)

select e1.id, e1.managerId, e2.managerId
from employees e1
left join employees e2 on (e1.manager = e2.employee)

答案 2 :(得分:0)

使用其他别名加入同一个表:

select a.username,a.manager,b.manager as director
from TableName a left join
TableName b on a.manager=b.username

结果:

username    manager     director
emp001      emp006      emp009
emp002      emp006      emp009
emp003      emp006      emp009
emp004      emp007      emp010
emp005      emp007      emp010
emp006      emp009      emp011
emp007      emp010      (null)
emp008      emp010      (null)
emp009      emp011      (null)
emp010      (null)      (null)
emp011      (null)      (null)

请参阅SQL Fiddle

中的结果