9

所以这实际上不是我的代码,而只是我正在尝试做的一个例子。理想情况下,我可以使用 INNER JOINS 和外键关系来获取数据,但在现实生活中我不能——这只是一个简单的例子。

SELECT [EmployeeID],
       [DepartmentID],
       (SELECT Title FROM Depts WHERE ID = [DepartmentID]) AS Department, 
       (SELECT Name FROM DeptHeads WHERE DeptName = Department) AS DepartmentLead
FROM   Employees E

我从一张表(员工)中获取数据。

我在子查询的 where 子句中使用该表 (DepartmentID) 中的一列,并从该表 (Department) 创建一个别名

然后我尝试做与上面相同的事情,除了在 where 子句中使用该别名。

我收到一条错误消息:

列名“部门”无效

有没有更好的方法让我做到这一点,或者解决这个问题?

4

3 回答 3

11

您不能使用刚刚定义的别名。你可以:

SELECT * FROM (

    SELECT [EmployeeID],
               [DepartmentID],
               (SELECT Title FROM Depts WHERE ID = [DepartmentID]) AS Department, 
               (SELECT Name FROM DeptHeads WHERE DeptName = Department) AS DepartmentLead
    FROM   Employees E

) Base

WHERE Base.Department = ...
于 2013-08-09T16:32:41.307 回答
6
;WITH MyCTE AS
(
    SELECT [EmployeeID],
       [DepartmentID],
       (SELECT Title FROM Depts WHERE ID = [DepartmentID]) AS Department, 
       (SELECT Name FROM DeptHeads WHERE DeptName = Department) AS DepartmentLead
    FROM   Employees E
)
SELECT *
FROM   MyCTE
WHERE  Department = 'IT'
于 2013-08-09T16:32:40.793 回答
1

方法一:

SELECT [EmployeeID],
[DepartmentID],
[Department],
(SELECT Name FROM DeptHeads WHERE DeptName = Department) AS DepartmentLead
FROM
(SELECT [EmployeeID],
       [DepartmentID],
       (SELECT Title FROM Depts WHERE ID = [DepartmentID]) AS Department, 
       FROM   Employees E ) E2

在 where 子句中使用 [Department] 别名

SELECT [EmployeeID],
[DepartmentID],
[Department],
(SELECT Name FROM DeptHeads WHERE DeptName = Department) AS DepartmentLead
FROM
(SELECT [EmployeeID],
       [DepartmentID],
       (SELECT Title FROM Depts WHERE ID = [DepartmentID]) AS Department, 
       FROM   Employees E ) E2
WHERE E2.Department = 'XYZ'

方法二:

SELECT E.[EmployeeID],
       E.[DepartmentID],
       D.Title AS Department, 
       DH.Name AS DepartmentLead
FROM   Employees E
LEFT JOIN Depts D ON E.[DepartmentID] = D.ID
LEFT JOIN DeptHeads DH ON D.Title = DH.DeptName
于 2013-08-10T03:06:13.820 回答