I am facing a problem in Unpivot the table.
My table structure is
x
Code Level1Name Level1Email Level2Name Level2Email Level3Name Level3 Email
1 aa aa@b.com bb bb@b.com cc cc@c.com
I need to convert this columns into Rows and need output like below
Code Info Level1 Level2 Level3
1 Name aa bb cc
1 Email aa@b.com bb@b.com cc@c.com
Advertisement
Answer
I would use apply
select t.code, v.*
from t cross apply
(values ('Name', t.Level1Name, t.Level2Name, t.Level1Name, Level3Name),
('Email', t.Level1Email, t.Level1Email, t.Level2Email, Level3Email)
) v(info, level1, level2, level3);