简体   繁体   English

SQL UnPivot 多列

[英]SQL UnPivot Multiple Columns

Im Using SSMS and I have a table that looks like this;我正在使用 SSMS,我有一张看起来像这样的表格;

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

I would like that data to look like this for reporting purpose;为了报告目的,我希望这些数据看起来像这样;

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

I think I need to use unpivot but I cannot get the headers into the rows and the comments to line up total I have 25 Requirements and 25 Comment fields.我想我需要使用 unpivot 但我无法将标题放入行中,并将评论排成一行 我有 25 个要求和 25 个评论字段。 on our paper form they have been static for years so I am not worried about future adding or removing new columns.在我们的纸质表格上,它们多年来一直是静态的,所以我不担心将来添加或删除新的列。

What stops you from using union of 25 selects?什么阻止您使用 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

I would suggest just using cross apply :我建议只使用cross apply

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

If you don't want to type 25 lines for values , you can use a spreadsheet to generate the code.如果您不想为values键入 25 行,则可以使用电子表格来生成代码。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM