简体   繁体   中英

T-SQL alias from CASE statement in SELECT clause not recognized in WHERE clause

Why does the first query work, but not the second? Why doesn't the alias get recognized when using the CASE statement? How can I fix the second query so the WHERE clause works?

SELECT
[a],
[b],
[c],
[d],
[e],
(CASE WHEN (SELECT COUNT(*) FROM Y WHERE Y.a = X.b AND Y.b IS NOT NULL) > 1 then 1 else 0 END) Q
FROM X
--WHERE Q = 1

SELECT
[a],
[b],
[c],
[d],
[e],
(CASE WHEN (SELECT COUNT(*) FROM Y WHERE Y.a = X.b AND Y.b IS NOT NULL) > 1 then 1 else 0 END) Q
FROM X
WHERE Q = 1

Error for 2nd query:

Invalid column name 'Q'

This is the correct behavior. If you want to use the alias in the where clause, use a subquery or CTE:

SELECT X.*
FROM (SELECT [a], [b], [c], [d], [e],
             (CASE WHEN (SELECT COUNT(*) FROM Y WHERE Y.a = X.b AND Y.b IS NOT NULL) > 1 then 1 else 0
              END) Q
      FROM X
     ) X
WHERE Q = 1;

A column alias cannot be used in the WHERE clause unless it is introduced in the FROM clause. Either repeat the whole expression or put the SELECT in a CTE and then work with the CTE to use the alias.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM