Search code examples
sqlpivotconverterstransposeunpivot

SQL all rows into one column - no concatenation


I have a table that I need has multiple rows and I to put them all into a new table.

All my rows need to be converted into one row.

+-------+-----------+-------+--------+
| ID    |   Name    |  Last | Gender |
+-------+-----------+-------+--------+
|  1    | Person1   | Last1 |   M    |
|  2    | Person2   | Last2 |   F    |
|  3    | Person3   | Last3 |   M    |
|  4    | Person4   | Last4 |   F    |
+-------+-----------+-------+--------+

I need to convert the above table to the below:

  +-------+------------+------------+
| NewID | ColumnName |    Value   |
+-------+------------+------------+
|     1 | ID         |    1       |
|     1 | Name       |    Person1 |
|     1 | Last       |    Last1   |
|     1 | Gender     |    M       |
|     2 | ID         |    2       |
|     2 | Name       |    Person2 |
|     2 | Last       |    Last2   |
|     2 | Gender     |    F       |
|     3 | ID         |    3       |
|     3 | Name       |    Person3 |
|     3 | Last       |    Last3   |
|     3 | Gender     |    M       |
|     4 | ID         |    4       |
|     4 | Name       |    Person4 |
|     4 | Last       |    Last4   |
|     4 | Gender     |    F       |
|       |            |            |
+-------+------------+------------+

Solution

  • The most general method is to use union all:

    select 'id' as columnname, cast(id as varchar(255)) as value from t union all
    select 'name', name as value from t union all
    select 'last', last as value from t union all
    select 'gender', gender as value from t;
    

    This should work in basically any database, although the cast to a string might vary. Some databases offer other solutions that are more efficient.