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

后端 未结 4 1331
青春惊慌失措
青春惊慌失措 2020-12-20 16:09

I have a (rather complicated) SQL statement where I select data from lots of different tables, and to cope with a bad legacy data structure, I have a couple of custom colum

4条回答
  •  一向
    一向 (楼主)
    2020-12-20 16:28

    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 WHERE
    ChannelValue > Limit * Percentage / 100
    

提交回复
热议问题