So this isn't actually my code, but just an example of what I'm trying to do. Ideally I'd be able to use INNER JOINS and foreign key relations to get data, but I can't in my real-life situation - this is just a simple example.
SELECT [EmployeeID],
[DepartmentID],
(SELECT Title FROM Depts WHERE ID = [DepartmentID]) AS Department,
(SELECT Name FROM DeptHeads WHERE DeptName = Department) AS DepartmentLead
FROM Employees E
I'm getting data from one table (Employees).
I'm using one of the columns from that table (DepartmentID) in a where clause in a subquery, and creating an alias from that (Department)
I'm then trying to do the same thing as above, except using that alias in the where clause.
I get an error saying:
Invalid column name "Department"
Is there a better way for me to do this, or a way around this?
The WHERE clause can contain non-correlated aliases and correlated aliases.
In PROC SQL, a column alias can be used in a WHERE clause, ON clause, GROUP BY clause, HAVING clause, or ORDER BY clause. In the ANSI SQL standard and ISO SQL standard, the value that is associated with a column alias does not need to be available until the ORDER BY clause is executed.
When using a self-join, it is important to use a logical SQL alias for each table. (Aliases are also useful for subqueries.
A subquery can be nested inside the WHERE or HAVING clause of an outer SELECT , INSERT , UPDATE , or DELETE statement, or inside another subquery.
You can't use aliases you just defined. You can:
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 = ...
;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'
Method 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
Using [Department] alias in where clause
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'
Method 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With