Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

tsql - Using Aliases in Where Clause or an Alternative Option?

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 know how to approach this?

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)

    Where City is NOT Null
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...