所以这实际上不是我的代码,而只是我正在尝试做的一个例子。理想情况下,我可以使用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
我从一个表(Employees)获取数据。
我在子查询的where子句中使用该表中的一列(DepartmentID),并从中创建别名(部门)
我正在尝试做与上面相同的事情,除了在where子句中使用该别名。
我收到错误说:
无效的列名称“部门”
有没有更好的方法让我这样做,或者解决这个问题?
答案 0 :(得分:6)
您不能使用刚刚定义的别名。你可以:
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 = ...
答案 1 :(得分:3)
;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'
答案 2 :(得分:0)
方法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'
方法2:
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