tsql - 根据哪个现有字段具有字符串匹配,为新字段分配值
问题描述
我的数据如下所示
Col1 COl2 Col3 COl4 COl5
Yes No No No No
No Yes No No No
我想创建一个新列,如下所示:
Col1 COl2 Col3 COl4 COl5 NEW_FIELD
Yes No No No No Col1
No Yes No No No Col2
因此,新字段采用匹配“是”的字段的名称(它仅出现在 Col1 和 Col5 之间的列之一中)。
我相信我可以用一个CASE
函数来做到这一点,但由于我大约有 10 列,所以语法有点笨拙,我想知道是否有MIN()
跨字段的更清晰的类型函数?
解决方案
coalesce()
您可以使用and获得第一个值case
:
select t.*,
(coalesce(case when col1 = 'Yes' then 'col1' end,
case when col2 = 'Yes' then 'col2' end,
case when col3 = 'Yes' then 'col3' end,
case when col4 = 'Yes' then 'col4' end,
case when col5 = 'Yes' then 'col5' end
)
) as new_field
实际上,coalesce()
不需要:
select t.*,
(case when col1 = 'Yes' then 'col1'
when col2 = 'Yes' then 'col2'
when col3 = 'Yes' then 'col3'
when col4 = 'Yes' then 'col4'
when col5 = 'Yes' then 'col5'
) as new_field
这似乎并不是特别“笨拙”。
推荐阅读
- python - 使用python在bar3d图上堆叠颜色
- c# - C# Rest api - 发布列表对象始终为空
- c++ - 如何在 Visual Studio 项目中使用 C++ 连接器
- optaplanner - 使用 contraints.drl 和 Spring Boot 的 Optaplanner 错误消息
- node.js - 为什么有些用户在 AWS ElasticBeanstalk 中部署后没有体验到更新?
- ansible - 如何使用 Ansible 获取 IP 地址?
- javascript - 函数“输入”和另一个允许“找到最大数字”的函数
- tensorflow - 将 ResNeXt 导入 Keras
- css - 仅当其同级具有无效类时,如何在 ::after 之后使用类
- python - Keras CNN,高训练低测试