如何在 MS SQL 中连接多个列的不同值?

How to concat distinct values over multiple columns in MS SQL?

我有一个table这样的

id type 1 type 2 type 3 type 4 type 5
1 a b b not available not available
2 c c a not available not available
3 not available not available not available not available not available

什么查询将帮助我对这些列中的不同值进行连接,并摆脱“不可用”,即:

id types
1 a, b
2 c, a
3

假设not available表示null,你可以这样做:

select
  x.id,
  group_concat(distinct t) as types
from (select id from t) x
left join (
  select id, type1 as t from t
  union all select id, type2 from t
  union all select id, type3 from t
  union all select id, type4 from t
  union all select id, type5 from t
) y on y.id = x.id
group by x.id
order by x.id

结果:

结果:

 id  types 
 --- ----- 
 1   a,b   
 2   a,c   
 3         

参见 db<>fiddle 中的示例。

您可以使用 CROSS APPLY

select
  id,
  string_agg(s.tp, ',') as types
from t
cross apply (
  select type1 union 
  select type2 union
  select type3 union
  select type4 union
  select type5  
) s(tp)
group by id
order by id;

db<>fiddle