需要替代加入sql server中的同一个表

时间:2016-09-26 04:00:37

标签: sql sql-server

我想要取 每行的下表中的部门名称。 [image 1]

Employee | Manager | Dept
---------+---------+-------------
Santosh  | Gyan    |
Rahul    |         | HR
Suresh   | Gyan    |
Gyan     |         | Technology
  • 每位经理都是员工。
  • IF部门名称不适用于员工,那么我必须在员工专栏中搜索他的经理并找到他的部门。

附加是预期的输出。 [image 2]

Employee | Manager | Dept
---------+---------+------------
Santosh  | Gyan    | Technology
Rahul    |         | HR
Suresh   | Gyan    | Technology
Gyan     |         | Technology

尝试过右连接同一个表,它会给出结果但在大表上占用太多时间。所以请提出另一种方法。

5 个答案:

答案 0 :(得分:1)

要获得查询性能,您可以使用Union All。

    SELECT EMPLOYEE, DEPT FROM EMPLOYEE WHERE DEPT IS NOT NULL
    UNION ALL
    SELECT E.EMPLOYEE, EM.DEPT FROM EMPLOYEE E
    INNER JOIN EMPLOYEE EM ON E.MANAGER = EM.MANAGER
    AND E.DEPT IS  NULL

答案 1 :(得分:1)

试试这个:

SELECT e.Employee, e.Manager, COALESCE(e.Dept, e1.Dept) Dept
FROM Employees e 
LEFT JOIN Employees e1 ON e1.Employee = e.Manager

OR:

SELECT e.Employee, e.Manager, COALESCE(e.Dept, t.Dept) Dept
FROM Employees e 
OUTER APPLY (SELECT dept FROM Employees e1 WHERE e1.employee = e.manager) t 

答案 2 :(得分:1)

您可以使用以下查询:

SELECT 
    Employee, 
    Manager,
    CASE WHEN Dept = '' THEN (
        SELECT t.Dept 
        FROM yourTable t 
        WHERE t.Employee = yourTable.Manager
    )
    ELSE Dept
    END As Dept
FROM 
    yourTable;

<强> [SQL Fiddle Demo]

这个查询就像你说的那样的SQL翻译;)。

答案 3 :(得分:1)

也许是在不同列表上的左连接

Declare @YourTable table (Employee varchar(50),Manager varchar(50),Dept varchar(50))
Insert Into @YourTable values
('Santosh','Gyan',''),
('Rahul','','HR'),
('Suresh','Gyan',''),
('Gyan','','Technology')

Select A.Employee
      ,A.Manager
      ,Dept = Isnull(B.Dept,A.Dept)
 From  @YourTable A
 Left Join (Select Distinct Employee,Dept from @YourTable Where Dept<>'') B
   on  A.Manager=B.Employee

甚至

Select A.Employee
      ,A.Manager
      ,Dept = case when A.Dept='' then B.Dept else A.Dept end
 From  @YourTable A
 Outer Apply (Select Dept from @YourTable Where Employee=A.Manager) B

返回

Employee    Manager Dept
Santosh     Gyan    Technology
Rahul               HR
Suresh      Gyan    Technology
Gyan                Technology

答案 4 :(得分:0)

试试这个,

S