如何使用where条件过滤CASE WHEN语句的数据?

How to filter data of CASE WHEN statement using where condition?

在盟友 CASE WHEN 条件作为列之后,我们可以过滤该列吗?

示例;

SELECT 
    CASE WHEN Number like '20%' THEN 'X'
   WHEN Number like '15%' or  Number like '16%'  THEN 'Y' ELSE 'Z'
   END Operation
   ,*
FROM 
TableA
where Operation like 'X'

我将 CASE WHEN 条件称为 'Operation',现在我只想在操作列中查看操作 'X'。

有没有办法在 SSMS 2012 中使用 where 子句过滤 CASE WHEN 条件?

将您的查询包装为 派生的 table,然后您可以将新列放在 WHERE 子句中:

select * 
from
(
    SELECT 
        CASE WHEN Number like '20%' THEN 'X'
       WHEN Number like '15%' or [Item Number] like '16%'  THEN 'Y' ELSE 'Z'
       END Operation
       ,*
    FROM 
    TableA
) dt
where Operation like 'X'

您必须在 WHERE 子句中重复 CASE 表达式,或者将其嵌套在另一个 SELECT 语句中。

您可以使用 APPLY :

SELECT A.*, AA.*
FROM TableA AS A CROSS APPLY
     ( VALUES (CASE WHEN Number like '20%'  
                    THEN 'X'
                    WHEN (Number like '15%' OR [Item Number] like '16%')  
                    THEN 'Y' ELSE 'Z'
               END ) 
     ) AA(Operation)
WHERE AA.Operation = 'X';

如果您还有其他过滤器,这会有所帮助。但是只有 WHERE Number LIKE '20%' 就好了。

加上你要申请的条件,你的语句等同于:

SELECT 'X' AS Operation, *
FROM 
TableA
where Number like '20%'

你不能在 ondition 中使用列别名 .. 如果你需要你可以使用 having(对结果值或子查询起作用)

SELECT 
    CASE WHEN Number like '20%' THEN 'X'
   WHEN Number like '15%' or  Number like '16%'  THEN 'Y' ELSE 'Z'
   END Operation
   ,*
FROM  TableA
HAVING Operation like 'X'

子查询和 where

select operation from (

  SELECT 
      CASE WHEN Number like '20%' THEN 'X'
     WHEN Number like '15%' or  Number like '16%'  THEN 'Y' ELSE 'Z'
     END Operation
     ,*
  FROM  TableA

  ) t 
  where operation = 'X'

否则你应该为 where 子句中的 case 重用相同的代码

SELECT 
    CASE WHEN Number like '20%' THEN 'X'
   WHEN Number like '15%' or  Number like '16%'  THEN 'Y' ELSE 'Z'
   END Operation
   ,*
FROM  TableA
 WHERE  CASE WHEN Number like '20%' THEN 'X'
   WHEN Number like '15%' or  Number like '16%'  THEN 'Y' ELSE 'Z'
   END like 'X'

只是另一种选择

使用 CTE

WITH CTE AS
(
  SELECT 
      CASE WHEN Number like '20%' THEN 'X'
     WHEN Number like '15%' or  Number like '16%'  THEN 'Y' ELSE 'Z'
     END Operation
     ,*
  FROM 
  TableA
)
SELECT *
FROM CTR
WHERE Operation = 'X';

使用 CASE 表达式

SELECT 
    CASE WHEN Number like '20%' THEN 'X'
   WHEN Number like '15%' or  Number like '16%'  THEN 'Y' ELSE 'Z'
   END Operation
   ,*
FROM 
TableA
WHERE CASE WHEN Number like '20%' THEN 'X'
           WHEN Number like '15%' or  Number like '16%'  THEN 'Y' 
           ELSE 'Z'
      END = 'X';

现在,让我们看看

I actually have multiple CASE WHEN statements but yeah using Number as a filter condition also works and simple.

好的,Number 列不需要 CASE 表达式

SELECT 'X' Operation,
       --Another CASE here if needed
       ,*
FROM 
TableA
WHERE Number like '20%';