4

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

1
  • 3
    Please use plain text format for sample data, instead of images. Commented Jul 1, 2016 at 13:01

2 Answers 2

8

try

select *
  from yourTable
  unpivot (
    Value
    for NewCol in (Value1, Value2, Value3,Value4, Value5)
  ) up
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks nazark, this works for me. appreciate the help here.
3

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.

1 Comment

Thanks for explaining all that.. nazark's response helped me get the required results

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.