sql - 在 where 子句中使用 case 语句

标签 sql select where-clause case-statement

您好,我遗漏了一些东西,因为我的代码错误。

select * from ##ScheduleDetail SD
left join ##HolidayFilterTbl HF on SD.Scheduledate = HF.Testdate

where (ScheduleDate = testdate)
and
(Case 
 when HF.IsHoliday = 1 then (overtime = 1 and makeup = 0)
 else
(overtime = 0 and Makeup = 0)
end
)
and
DOW = 5 
order by ActivityStartTime
我尝试了几种组合,每个组合都在第一个等号或第二个等号处出错。我错过了什么?

最佳答案

case的分支表达式只能返回值,不能在 where 中计算额外的表达式健康)状况。但是,您可以使用 and 模拟这种行为。和 or逻辑运算符:

select    *
from      ##ScheduleDetail SD
left join ##HolidayFilterTbl HF on SD.Scheduledate = HF.Testdate
where     (ScheduleDate = testdate) and
          ((HF.IsHoliday = 1 and overtime = 1 and makeup = 0) or
           (overtime = 0 and Makeup = 0)) and
          DOW = 5 
order by  ActivityStartTime
请注意,您有 makeup = 0case 的两个分支上问题中的表达式(或答案中 or 的两侧),因此您可以从中提取它并稍微简化条件:
select    *
from      ##ScheduleDetail SD
left join ##HolidayFilterTbl HF on SD.Scheduledate = HF.Testdate
where     ScheduleDate = testdate and
          makeup = 0 and
          ((HF.IsHoliday = 1 and overtime = 1) or
           overtime = 0) and
          DOW = 5 
order by  ActivityStartTime

关于sql - 在 where 子句中使用 case 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65116090/

相关文章:

mysql - 在存储过程中使用 LIKE 并同时转义注入(inject)

php - MySQL 错误 - 插入时出现 "You have an error in your SQL syntax"

php - 更新值而不删除其他值并删除 PHP CONCAT 列中的现有值

javascript - 使用 jquery 创建并复制选择框

c# - `Where` 子句返回空列表,即使逻辑测试是 `true`

如果设置了另一个字段中的值,MYSQL 会隐藏字段数据

SQL 服务器 : concatenate values and ignore null or blank values

mysql:按like排序?

mysql - 如何使用 select 的输出作为 MySQL 函数的输入?

MySQL:查找没有提交的用户