1

Using Select top 1 statement I have to retrieve data from an 8 column table without any unique key. Now I want to transpose this table into two columns: original column name to the first and its respective value to second.

An original table like this:

Column1 | Column2 | Column3 | Column4 
55 | 108 | 555 | 85

And the expected result:

ColumnName | Value
Column1 | 55
Column2 | 108
Column3 | 555
Column4 | 85
András Váczi
31.8k13 gold badges103 silver badges152 bronze badges
asked Sep 15, 2015 at 12:29
0

1 Answer 1

5

There's a T-SQL construct called UNPIVOT which is designed for this. But in my experience, you'll have more luck with APPLY as per my code below:

SELECT *
FROM YourTable t
CROSS APPLY
 (SELECT 'Col1', Column1
 UNION ALL
 SELECT 'Col2', Column2
 UNION ALL
 SELECT 'Col3', Column3
 UNION ALL
 SELECT 'Col4', Column4
 ) u (columnName, Value)
 ;
András Váczi
31.8k13 gold badges103 silver badges152 bronze badges
answered Sep 15, 2015 at 13:03
3
  • Thank you instead of Select * From YourTable t which add two more columns (columnName and Value) to original select statement Select u.columnName, u.Value from YourTable t CROSS Apply(...............); does a perfect job. Commented Sep 15, 2015 at 17:12
  • Does not work for me, there is an error indicating SELECT is on the wrong place, apparently....probably something with the syntax. I am using MySQL however. Commented Jul 24, 2019 at 13:04
  • I can’t guarantee this will work in MySQL. The syntax is valid in SQL Server though. Commented Jul 25, 2019 at 3:15

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.