sql服务器中不同列有标签时,如何设置一列显示严格标签或null

When there are labels in different columns, how to set a column to show a strict label or null in sql server

我在 sql 服务器中有一个 table,如下所示:

Name  Col1  Col2  Col3  Col4 
A     din   gla   gif   cla 
B     gla   cla   gif   din
C     din   gif   cla   null  --gla is missing
D     null  cla   gla   null  --din and gif is missing

只有 "name" 在其任何列中是否有标签才重要。我需要的是 return 一个结果集,每列代表一个定义的值,如下所示:

Name  Col1  Col2  Col3  Col4 
A     din   gla   gif   cla
B     din   gla   gif   cla
C     din   null  gif   cla
D     null  gla   null  cla

我已经通过如下查询管理了它:

select name,
       col1 = case when col1='din' or col2='din' or col3='din' or col4='din' then 'din' else null end,
       ...
from table

然而,原来有很多列,而不是只有4个,而且这种方式对我来说似乎不是最好的。我想知道你是否可以推荐更好的方法。如有任何建议,我们将不胜感激。

你的方法很好。另一种方法是使用 apply:

select t.name, v.*
from t cross apply
     (select max(case when col = 'din' then 'din' end) as din,
             max(case when col = 'gla' then 'gla' end) as gla,
             . . .
      from (values (col1), (col2), (col3), (col4)) v(col
     ) v;