0

Im Using SSMS and I have a table that looks like this;

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. on our paper form they have been static for years so I am not worried about future adding or removing new columns.

1
  • Could be done using UNION ALL. Commented Mar 23, 2020 at 9:47

3 Answers 3

2

What stops you from using union of 25 selects?

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I applied this and a few mins of work the view was created and the report is ready to build!
2

I would suggest just using 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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.