[英]SQL: Greater than or equal to in where clause based on case condition?
I want to select such that if @reporteetype
is 'immediate'
then I would want to select rows where level is equal to 1, otherwise where level is greater than 2. 我想选择这样,如果@reporteetype
是'immediate'
那么我想选择level 等于 1的行,否则level 大于 2。
select a, b, c, level
from table1
where col1 ='x' and
CASE @reporteetype WHEN 'immediate' THEN level = '2'
WHEN 'other' THEN level > 2
else 1 = 1
END
This is a simplified version of my scenario. 这是我的方案的简化版本。 I do not want to use dynamic query. 我不想使用动态查询。 I want to know if this could be done using case? 我想知道这是否可以用案例来完成?
You can do it using combinations of AND
and OR
conditions: 您可以使用AND
和OR
条件的组合来执行此操作:
SELECT
a, b, c, level
FROM table1
WHERE
col1 = 'x'
AND (
(@reporteetype = 'immediate' AND level = 2)
OR (@reporteetype = 'other' AND level > 2)
)
Additional reading: 补充阅读:
Answer suggested by @Felix Pamittan is more efficient, however if you want to use CASE Expression, then it can be helpful: @Felix建议的答案Pamittan更有效,但是如果你想使用CASE Expression,那么它会有所帮助:
SELECT a
, b
, c
, level
FROM table1
WHERE col1 = 'x'
AND ( ( CASE WHEN @reporteetype = 'immediate' THEN '2'
END ) = level
OR ( CASE WHEN @reporteetype = 'other' THEN '2'
END ) > level
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.