SQL Server:in...case...in WHERE 子句
我需要编写这样的查询:
Select [something]
Where
condition in
case
when (if another_condition = A and 3rd Condition = B) then (C,D)
when (if another_condition = N and 3rd Condition = E) then (F,G)
else (J,K)
end
本质上,我想要的是如果满足 A 和 B,则条件可以设置为 C 或 D,如果满足 N 或 E,则条件可以设置为 F 或G,否则条件设置为 J 或 K。 然而,当我运行这个时,我不断得到 关键字“Case”附近的语法不正确。
请帮忙!谢谢!
I need to code up a query for something like this:
Select [something]
Where
condition in
case
when (if another_condition = A and 3rd Condition = B) then (C,D)
when (if another_condition = N and 3rd Condition = E) then (F,G)
else (J,K)
end
essentially, what I want is if A and B are met, condition could be set to either C or D, if N or E are met, then condition could be set to F or G, else condition set to J or K.
However, when I run this, I kept getting
Incorrect syntax near the keyword 'Case'.
Please help! Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许是这样的:
在 where 子句中混合使用 and 和 or 时要非常小心。括号很重要。
Maybe this:
Be very careful about mixing and's and or's in a where clause. Parenthesis are important.
怎么样 - UNION 子查询将为您提供子查询中的完整结果集。然后你可以说'WHERE条件IN'(子查询)。像这样:
How about this - the UNION subquery will give you the full result set within the subquery. Then you can say 'WHERE condition IN ' (subquery). Like this:
我可能会采用 G Mastro 将查询扩展为布尔表达式的方法。虽然嵌套查询方法可以工作,但在我看来,代码的意图不太明显。
话虽如此,如果你的 CASE 语句中有很多情况,你可能需要考虑重塑你的数据,因为无论你如何编写查询,它都归结为一个大的布尔表达式。
I'd probably go with G Mastro's approach of expanding the query as a Boolean expression. While the nested query approach will work, the intent of the code is less obvious IMO.
Having said that, if there are a lot of cases in your CASE statement, you may want to consider reshaping your data, because no matter how you write the query, it boils down to a big Boolean expression.