0

我有以下 SQL 语句:

select * from Leaves inner join LeaveDetails on Leaves.LeaveId= LeaveDetails.LeaveId 
inner join Employee on Leaves.EmployeeCode =  Employee.EmployeeCode
inner join LeaveType on Leaves.LeaveTypeId= LeaveType.LeaveTypeId 
inner join LeaveStatus on Leaves.StatusId = LeaveStatus.StatusId 
inner join Employee_organizationaldetails on Employee_organizationaldetails.EmployeeCode=Employee.EmployeeCode 
where Leaves.LeaveId = 7295 

Employee_organizationdetails 包含另一个名为报告官员的列,它是同一个 Employee 表的外键。现在我需要获取员工的姓名。

如何编写上述查询,以便在不获取执行查询的情况下获取报告官员的姓名作为另一列

select (FirstName + ' ' + LastName) as name from Employee where EmployeeCode = ReportingTo

这里的 ReportingTo 是员工代码。我需要垂直加入它们。类似于联合运算符的东西

4

2 回答 2

1

您想重新加入Employee表的另一个“副本”:

select *, (ro.FirstName + ' ' + LastName) as ReportingName
from Leaves inner join LeaveDetails on Leaves.LeaveId= LeaveDetails.LeaveId 
inner join Employee on Leaves.EmployeeCode =  Employee.EmployeeCode
inner join LeaveType on Leaves.LeaveTypeId= LeaveType.LeaveTypeId 
inner join LeaveStatus on Leaves.StatusId = LeaveStatus.StatusId 
inner join Employee_organizationaldetails on Employee_organizationaldetails.EmployeeCode=Employee.EmployeeCode  left outer join
Employee ro
on ro.EmployeeCode = ReportingTo
where Leaves.LeaveId = 7295;

您可能不想要*- 我认为这只是问题的简写。最好明确列出列,特别是因为存在重复的列名。

于 2013-05-20T11:17:04.240 回答
0

可能这对您有帮助-

SELECT 
      *
    , ReportingName = ro.FirstName + ' ' + LastName
FROM (
    SELECT *
    FROM dbo.Leaves l
    WHERE l.LeaveId = 7295
) l
JOIN dbo.LeaveDetails ld ON l.LeaveId = ld.LeaveId 
JOIN dbo.Employee e ON l.EmployeeCode =  e.EmployeeCode
JOIN dbo.LeaveType lt ON l.LeaveTypeId = lt.LeaveTypeId 
JOIN dbo.LeaveStatus ls ON l.StatusId = ls.StatusId 
JOIN dbo.Employee_organizationaldetails e2 ON e2.EmployeeCode = e.EmployeeCode  
LEFT JOIN dbo.Employee ro ON ro.EmployeeCode = ReportingTo
于 2013-05-20T11:24:09.863 回答