SQL所有行都放在一列中 - 没有连接

时间:2017-10-31 21:39:38

标签: sql pivot converter transpose unpivot

我有一个我需要的表有多行,我把它们全部放到一个新表中。

我的所有行都需要转换成一行。

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

我需要将上表转换为以下内容:

  +-------+------------+------------+
| 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       |
|       |            |            |
+-------+------------+------------+

2 个答案:

答案 0 :(得分:1)

联盟快乐解决方案。

select 'id' as columnname, id as value from table
union all
select 'name' as columnname, name as value  from table
union all
.e
.t
.c

答案 1 :(得分:1)

最常用的方法是使用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;

这应该基本上适用于任何数据库,尽管对字符串的强制转换可能会有所不同。有些数据库提供了更高效的其他解决方案。