使用“结果表达式”来自 WHERE 子句中的 CASE 表达式
是否可以通过使用 WHERE
子句中的 CASE
表达式的结果表达式 (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'
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SQL-Server 需要表别名:
SQL-Server requires a table alias:
我认为你必须使用
HAVING
而不是WHERE
:编辑:
顺便说一句,你为什么不直接使用:
I think you will have to use
HAVING
instead ofWHERE
:EDIT:
By the way, why don't you just use: