Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Convert multiple columns to rows

I have a table in below format enter image description here I need to convert it to this format

enter image description here

SO basically i am looking to convert multiple columns to rows. Can some one help me with this?

Thanks

like image 299
Tayyab Amin Avatar asked Sep 13 '25 16:09

Tayyab Amin


2 Answers

try

select *
  from yourTable
  unpivot (
    Value
    for NewCol in (Value1, Value2, Value3,Value4, Value5)
  ) up
like image 140
nazark Avatar answered Sep 17 '25 00:09

nazark


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.

like image 24
David Rushton Avatar answered Sep 16 '25 22:09

David Rushton