Use “result expression” from CASE expression in WH

2019-02-25 09:59发布

问题:

Is it possible to filter records in SQL Server by using a result expression (weight_class) from a CASE expression in the WHERE clause? I can't get it to work because I get an error saying:

Invalid column name 'weight_class'

Code:

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

This is how I want to do:

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'

回答1:

SQL-Server requires a table alias:

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'


回答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'


回答3:

I think you will have to use HAVING instead of 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'

EDIT:

By the way, why don't you just use:

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