Invalid column name error in WHERE clause, column selected with CASE Invalid column name error in WHERE clause, column selected with CASE sql-server sql-server

Invalid column name error in WHERE clause, column selected with CASE


The only part of the SQL Statement where it is valid to use an alias declared in the SELECT list is the ORDER BY clause. For other parts of the query you just have to repeat the whole CASE expression and trust the optimiser to recognise it is the same.

If you are on SQL2005+ you can use a CTE to avoid this issue which sometimes helps with readability.

WITH YourQuery As( SELECT     Limit,      Percentage,     CASE channel         WHEN 1 THEN channel_1         WHEN 2 THEN channel_2         ...         ELSE 0     END AS ChannelValue,     CASE channelu         WHEN 1 THEN channelu_1         WHEN 2 THEN channelu_2         ...         ELSE '0'     END AS ChannelWithUnit,     ... FROM )select ...FROM YourQuery WHEREChannelValue > Limit * Percentage / 100


You cannot use ChannelValue column name in the where clause at the same select level.
You will have to put this whole select in a subquery.

select ....from ( your select query) as innerSelectwhere ChannelValue > Limit * p.Percentage / 100


You can use a CTE - something like

WITH CTE AS(SELECT      ...,      CASE channel          WHEN 1 THEN channel_1          WHEN 2 THEN channel_2          ...          ELSE 0      END AS ChannelValue,      CASE channelu          WHEN 1 THEN channelu_1          WHEN 2 THEN channelu_2          ...          ELSE '0'      END AS ChannelWithUnit,      ...  FROM  )SELECT * FROM CTEWHERE ChannelValue > Limit * p.Percentage / 100