I have a table in below format
I need to convert it to this format
SO basically i am looking to convert multiple columns to rows. Can some one help me with this?
Thanks
try
select *
from yourTable
unpivot (
Value
for NewCol in (Value1, Value2, Value3,Value4, Value5)
) up
Converting columns to rows is called unpivoting. Converting rows to columns is pivoting.
One approach to unpivoting data is to combine the apply operator with a table value constructor.
This example uses a common table expression (CTE) to return 3 sample records.
Id ColumnOne ColumnTwo ColumnThree
1 a b c
2 d e f
3 g h i
Example
-- Unpivoting with apply and VALUES.
WITH SampleData AS
(
/* This CTE returns 3 sample records.
*/
SELECT
cte.*
FROM
(
VALUES
(1, 'a', 'b', 'c'),
(2, 'd', 'e', 'f'),
(3, 'g', 'h', 'i')
) AS cte(Id, ColumnOne, ColumnTwo, ColumnThree)
)
SELECT
sd.Id,
ca.*
FROM
SampleData AS sd
CROSS APPLY
(
VALUES
(ColumnOne),
(ColumnTwo),
(ColumnThree)
) AS ca (ColumnFour)
;
The returned output looks like this:
Id ColumnFour
1 a
1 b
1 c
2 d
2 e
2 f
3 g
3 h
3 i
Personally I prefer @nazark's approach. Using the UNPIVOT operator helps others to follow the intention of your code. If that answer helped you please accept it. Accepting answers rewards the contributor for his/her efforts and helps other people with the same problem to find a working answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With