sql - Case Statements in SQL - Nature of the Process
问题描述
I am writing a case statement in SQL to determine if an employee is a veteran or veteran spouse. There are three fields that contain the data and the logic would be:
1) If any of the three fields indicates veteran, the person is a veteran 2) If none indicate veteran but the last one indicates spouse, the person is a spouse
I have written a case statement that seems to work:
CASE
WHEN Flag1 = 'Vet' THEN 'Veteran'
WHEN Flag2 = 'Vet' THEN 'Veteran'
WHEN Flag3 = 'Vet' THEN 'Veteran'
WHEN Flag3 = 'Spouse' THEN 'Veteran Spouse'
ELSE 'Non Veteran/Spouse'
END
I am wondering if this works because there are no scenarios in my data that are causing to fail, not because it is written correctly. For example, I have no data where one of the first 2 flags says vet and flag 3 is spouse (which I would expect to show as a vet). What I want to know is: when the case statement hits it's first when that is positive, does it take action on the record and move to the next row or does it look at the next when and take action if those conditions are met as well changing the response (example: if flag1 is vet the case statement output is Veteran. If the same row had the word spouse in flag3 would the record be changed to Veteran Spouse?)
解决方案
你所拥有的是正确的。数据库将按顺序评估WHEN
条件并使用匹配的第一个条件。
为了好玩,你也可以这样写:
CASE WHEN 'Vet' IN (Flag1, Flag2, Flag3) THEN 'Veteran'
WHEN Flag3 = 'Spouse' THEN 'Veteran Spouse'
ELSE 'Non Veteran/Spouse'
END
如果这些值位于您可以加入的小型查找表中,那就更好了。
推荐阅读
- node.js - 在 gulp 任务后无法在 vscode 上为 typescript 运行调试器,调试器运行未编译的代码
- vue.js - Nuxt基于域名的动态布局?
- macos - Mac 的 Clickhouse 安装失败:“不支持 AppleClang,您应该从 brew 安装 clang。”
- javascript - 在使用隐藏画布上传之前旋转图像
- python - 在 Python 中比较两个字典的值,并返回差值大于 2 的值的键
- c# - 从图片框保存图像时参数无效异常
- jquery - Jquery如何在数据属性数组中选择包含特定值的元素?
- reactjs - “IntrinsicAttributes & Props”类型上不存在 className
- java - 如何将主类中的对象添加到其他类Java中的ArrayList
- laravel - 在 laravel 6 中未添加主键作为对外键的引用