I feel like all the answers showing use of a CTE or Sub Query are sufficient fixes for this, but I don't see anyone getting to the heart of why OP has a problem. The reason why what OP suggested doesn't work is due to logical query processing order here:
- FROM
- ON
- JOIN
- WHERE
- GROUP BY
- WITH CUBE/ROLLUP
- HAVING
- SELECT
- DISTINCT
- ORDER BY
- TOP
- OFFSET/FETCH
I believe this contributes to the answer greatly, because it explains why issues like this one occur. WHERE
is always processed before SELECT
making a CTE or Sub Query necessary for many functions. You will see this a lot in SQL Server.