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

时间:2019-01-16 15:49:31

标签: sql sql-server tsql ssms ssms-2012

盟友在以情况为列时可以过滤该列吗?

示例;

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条件称为“操作”,现在我只想在“操作”列中看到“ X”操作。

是否可以使用SSMS 2012中的where子句过滤CASE WHEN条件?

6 个答案:

答案 0 :(得分:3)

将查询打包为派生表,然后可以将新列放在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'

答案 1 :(得分:3)

您可以使用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%'很好。

答案 2 :(得分:2)

在您要应用的条件下,您的声明等同于:

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

答案 3 :(得分:1)

还有另一个选择

使用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';

现在,让我们看看your last comment

  

我实际上有多个CASE WHEN语句,但是使用Number作为过滤条件也很简单。

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

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

答案 4 :(得分:0)

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

答案 5 :(得分:0)

如果需要,您不能在ondition中使用列别名。可以使用hading(对结果值或子查询起作用)

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'

子查询以及位置

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子句

,您应该重用相同的代码
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'