首页 > 解决方案 > 根据哪个现有字段具有字符串匹配,为新字段分配值

问题描述

我的数据如下所示

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()跨字段的更清晰的类型函数?

标签: tsql

解决方案


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

这似乎并不是特别“笨拙”。


推荐阅读