Rajesh Pai
Rajesh Pai

Reputation: 13

Convert Single Row To Single Column Using Pivot/unpivot In Sql Server

I have a table with a single row as below:

+-------+-------+-------+-------+-------+
| (Col1)| (Col2)| (Col3)| (Col4)| (Col5)|
+-------+-------+-------+-------+-------+
| Data1 | Data2 | Data3 | Data4 | Data5 |
+-------+-------+-------+-------+-------+

What I want to do seems very simple, but I am not able to find any examples of it anywhere. All I want is to convert the above row into a single column like so:

+-------------+
|(Column Name)|
+-------------+
|Data1        |
+-------------+
|Data2        |
+-------------+
|Data3        |
+-------------+
|Data4        |
+-------------+
|Data5        |
+-------------+

I appreciate any help.

Upvotes: 1

Views: 3669

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270773

I would recommend using apply:

select v.col
from t cross apply
     (values (col1), (col2), (col3), (col4), (col5)) v(col);

I strongly recommend apply over unpivot. However, they are not 100% equivalent, because unpivot filters out NULL values.

Upvotes: 2

Related Questions