Using Aliases in Where Clause or an Alternative Option?

前端 未结 2 1914
你的背包
你的背包 2020-11-30 11:04

How do I get this to work, it works without the Where Clause, otherwise with the Where clause, i get the obvious error, but that\'s basically what needs to be done, anyone k

2条回答
  •  伪装坚强ぢ
    2020-11-30 11:52

    You can't use the alias in the WHERE clause. Either repeat the expression (messy) or else put your SELECT in a subquery and then put the WHERE clause in the outer query:

    SELECT Id, Name, City, State
    FROM
    (
         SELECT
             ID, 
             Name,
             CASE T.N 
                 WHEN 1 THEN City1
                 WHEN 2 THEN City2
                 WHEN 3 THEN City3
             END AS City,
             CASE T.N 
                 WHEN 1 THEN State1
                 WHEN 2 THEN State2
                 WHEN 3 THEN State3
             END AS State
         FROM YourTable
         CROSS JOIN (VALUES(1),(2),(3)) AS T(N)
    ) T1
    WHERE City IS NOT NULL
    

提交回复
热议问题