在WHERE子句中使用CASE表达式中的“结果表达式”

时间:2010-12-30 11:50:13

标签: sql sql-server case where

是否可以使用CASE子句中WHERE表达式的结果表达式(weight_class)来过滤SQL Server中的记录?我无法让它工作,因为我收到一个错误说:

  

无效的列名'weight_class'

代码:

SELECT 
    first_name, last_name, 
    weight_class = CASE
                      WHEN weight < 172 THEN 'Welterweight'
                      WHEN weight <= 192 THEN 'Middleweight'
                      WHEN weight <= 214 THEN 'Light heavyweight'
                      WHEN weight <= 220 THEN 'Cruiserweight'
                      ELSE 'Heavyweight'
                   END
FROM 
    athletes

这就是我想要做的事情:

SELECT 
    first_name, last_name, 
    weight_class = CASE
                      WHEN weight < 172 THEN 'Welterweight'
                      WHEN weight <= 192 THEN 'Middleweight'
                      WHEN weight <= 214 THEN 'Light heavyweight'
                      WHEN weight <= 220 THEN 'Cruiserweight'
                      ELSE 'Heavyweight'
                   END
FROM 
    athletes
WHERE 
    weight_class = 'Cruiserweight'

3 个答案:

答案 0 :(得分:7)

SQL-Server需要表别名:

SELECT * from
 (
 SELECT first_name, last_name, 
        CASE
 WHEN weight<172 THEN 'Welterweight'
 WHEN weight<=192 THEN 'Middleweight'
 WHEN weight<=214 THEN 'Light heavyweight'
 WHEN weight<=220 THEN 'Cruiserweight'
  ELSE 'Heavyweight'
  END AS weight_class 
  FROM athletes
 ) as t
 WHERE weight_class = 'Cruiserweight'

答案 1 :(得分:2)

 SELECT * from
 (
 SELECT first_name, last_name, 
        CASE
 WHEN weight<172 THEN 'Welterweight'
 WHEN weight<=192 THEN 'Middleweight'
 WHEN weight<=214 THEN 'Light heavyweight'
 WHEN weight<=220 THEN 'Cruiserweight'
  ELSE 'Heavyweight'
  END AS weight_class 
  FROM athletes
 ) t
 WHERE weight_class = 'Cruiserweight'

答案 2 :(得分:0)

我认为您必须使用HAVING代替WHERE

SELECT first_name, last_name, weight_class =
CASE
WHEN weight<172 THEN 'Welterweight'
WHEN weight<=192 THEN 'Middleweight'
WHEN weight<=214 THEN 'Light heavyweight'
WHEN weight<=220 THEN 'Cruiserweight'
ELSE 'Heavyweight'
END
FROM athletes
HAVING weight_class = 'Cruiserweight'

编辑:

顺便问一下,你为什么不使用:

SELECT first_name, last_name, weight_class =
CASE
WHEN weight<172 THEN 'Welterweight'
WHEN weight<=192 THEN 'Middleweight'
WHEN weight<=214 THEN 'Light heavyweight'
WHEN weight<=220 THEN 'Cruiserweight'
ELSE 'Heavyweight'
END
FROM athletes
WHERE weight > 214 AND weight <= 200