SQL UnPivot 多列

SQL UnPivot Multiple Columns

我正在使用 SSMS,我有一个 table 看起来像这样;

ID   / Req1 / Req1Comment  / req2 / req2Commnet  /
1   /  yes /              / no   /  needs work  /
2  /  no  / not working  / yes  /              /

出于报告目的,我希望数据看起来像这样;

ID   / Requirement  / Requirement Status /  Comments
  1  /    Req 1    /   Yes              /
  1  /    Req 2   /    no               / Needs Work

我想我需要使用 unpivot,但我无法将 headers 放入行中,并且无法将评论排成一列 我有 25 个要求和 25 个评论字段。在我们的纸质表格上,它们多年来一直是静态的,所以我不担心将来添加或删除新列。

是什么阻止您使用 25 个选择的并集?

select ID, 'Req 1' as Requirement, Req1 as RequirementStatus, Req1Comment as Comments from t
union all
select ID, 'Req 2' as Requirement, req2 as RequirementStatus, req2Comment as Comments from t
union all
...
select ID, 'Req 25' as Requirement, req25 as RequirementStatus, req25Comment as Comments from t
declare @t table
(
id int identity,
Req1 varchar(10),
Req1Comment varchar(20),
Req2 varchar(10),
Req2Comment varchar(20)
)

insert into @t (Req1, Req1Comment, Req2, req2Comment)
values
('yes', null, 'no', 'needs work'),
('no', 'not working', 'yes', '');


select id, 'Req 1' as Requirement, Req1 as [Requirement Status], Req1Comment as Comments
from @t
union all
select id, 'Req 2', Req2, Req2Comment
from @t;

select id, concat('Req ', v.val) as Requirement, case v.val when 1 then Req1 else Req2 end as [Requirement Status], case v.val when 1 then Req1Comment else Req2Comment end as Comments
from @t as t
cross apply (values(1), (2)) as v(val);

select id, concat('Req ', v.val) as Requirement, 
    choose(v.val, Req1, Req2) as [Requirement Status], 
    choose(v.val, Req1Comment, Req2Comment) as Comments
from @t as t
cross apply (values(1), (2)) as v(val);

我建议只使用 cross apply:

select t.id, v.*
from t cross apply
     (values ('Req 1', Req1, Req1Comment),
             ('Req 2', Req2, Req2Comment),
             . . .
     ) v(requirement, status, comments);

如果您不想为 values 输入 25 行,您可以使用电子表格生成代码。