I have a fairly simple SQL statement to get some results from a couple of tables. One of the columns is generated from an inline SQL statement. While I seem to be able to order by this column, trying to filter with it says that the column is invalid. Here is my code and error:
SELECT
e.Title as Title,
-- Get earliest start time and latest end time
(SELECT TOP 1 l.StartTime FROM Locations l WHERE l.EventID = e.EventID ORDER BY l.StartTime ASC) as EarliestStartTime,
(SELECT TOP 1 l.EndTime FROM Locations l WHERE l.EventID = e.EventID ORDER BY l.EndTime DESC) as LatestEndTime
FROM
Events e
WHERE
e.UserID = @UserID
AND LatestEndTime < DATEADD(DAY, GETDATE(), 1)
ORDER BY
EarliestStartTime ASC
Error:
Invalid column name 'LatestEndTime'.
If I remove the AND LatestEndTime < DATEADD(DAY, GETDATE(), 1) then the statement works perfectly.
You can’t refer to columns by alias in the
whereclause. Either write it out, repeating the column definition:Or use a subquery to name the column: