Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 在case-when语句中是否有使用条件的方法?_Sql_Sql Server_Sql Server 2008 - Fatal编程技术网

Sql 在case-when语句中是否有使用条件的方法?

Sql 在case-when语句中是否有使用条件的方法?,sql,sql-server,sql-server-2008,Sql,Sql Server,Sql Server 2008,我的查询(不会运行): 从表A中选择* 式中(模式=1时,吨位>1000 当模式=2时,则吨位>5000 其他吨位1000)或 (模式=2且吨位>5000)或 ((模式不在(1,2)或模式为空)且吨位1000时,则为1 当模式=2且吨位>5000时,则为1 当吨位

我的查询(不会运行):

从表A中选择*
式中(模式=1时,吨位>1000
当模式=2时,则吨位>5000
其他吨位<-1
)
我试图做的是根据另一列(模式)选择不同的过滤临界值(吨位)

但是,由于
的原因,这将不起作用


有办法解决吗?

您不需要
案例

where (mode = 1 and Tonnage > 1000) or
      (mode = 2 and Tonnage > 5000) or
      ( (mode not in (1, 2) or mode is null) and Tonnage < -1)
其中(模式=1且吨位>1000)或
(模式=2且吨位>5000)或
((模式不在(1,2)或模式为空)且吨位<-1)

您也可以通过案例陈述来实现这一点,对两者之间的绩效结果感到好奇

SELECT * 
FROM TABLE A
WHERE (case when mode = 1 and Tonnage > 1000 then 1
          when mode = 2 and Tonnage > 5000 then 1
          when tonnage < -1 then 1
          else 0 end
    ) = 1
选择*
从表A
式中(当模式=1且吨位>1000时,则为1
当模式=2且吨位>5000时,则为1
当吨位<-1时,则为1
其他0结束
) = 1

您不能将条件拆分为每个select语句,也不能通过union连接数据集?计算案例然后进行比较的可能重复,这通常比直接表达式效率低,因为优化器无法使用任何筛选器或统计信息。它“必须”计算每行的结果,然后进行比较。(实际上不必这样做,但由于
CASE
的短路逻辑,优化起来会很复杂。)如果您已经在进行表扫描,则没有太大区别。
SELECT * 
FROM TABLE A
WHERE (case when mode = 1 and Tonnage > 1000 then 1
          when mode = 2 and Tonnage > 5000 then 1
          when tonnage < -1 then 1
          else 0 end
    ) = 1